我有一系列数字,我需要确保它们是唯一的.我在互联网上找到了下面的代码片段,它的工作情况很好,直到数组中的数字为零.我发现这个其他脚本在SO上看起来几乎就像它,但它不会失败.
所以为了帮助我学习,有人可以帮我确定原型脚本出错的地方吗?
Array.prototype.getUnique = function() {
var o = {}, a = [], i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
for (e in o) {a.push (e)};
return a;
}
Run Code Online (Sandbox Code Playgroud)
当我减少数组时,我试图将数字设为零,但我不清楚这个函数的行为
[].reduce(function(previousValue, currentValue){
return Number(previousValue) + Number(currentValue);
});
Run Code Online (Sandbox Code Playgroud)
结果
TypeError: Reduce of empty array with no initial value
Run Code Online (Sandbox Code Playgroud)
似乎如果数组是空的我无法减少它
[""].reduce(function(previousValue, currentValue){
return Number(previousValue) + Number(currentValue);
});
Run Code Online (Sandbox Code Playgroud)
结果
""
Run Code Online (Sandbox Code Playgroud)
如果数组中唯一的元素是空字符串,则检索空字符串