我一直在寻找一种在数组中查找多个值的解决方案,并找到了这个:
function find_duplicate_in_array(arra1) {
var object = {};
var result = [];
arra1.forEach(function(item) {
if (!object[item])
object[item] = 0;
object[item] += 1;
})
for (var prop in object) {
if (object[prop] >= 2) {
result.push(prop);
}
}
return result;
}
console.log(find_duplicate_in_array([1, 2, -2, 4, 5, 4, 7, 8, 7, 7, 71, 3, 6]));
我不明白发生了什么。具体来说:
object[item] = 0;
object[item] +=1;
所以...对于数组中的每个元素,如果该元素不在临时对象中,则在索引 0 处添加元素,然后添加 1?
这是怎么回事?请有人逐行解释。我是 JavaScript 新手。
最佳答案
这是代码,每行都有注释!希望对您有所帮助 ;)
function find_duplicate_in_array(arra1) {
// Temporary count of each item in the input array/
var object = {};
// Final result containing each item that has been seen more than one time.
var result = [];
// For each item of the array...
arra1.forEach(function (item) {
// If it is not in the temporary object, initialize it to 0.
if(!object[item])
object[item] = 0;
// Add one since we just have found it!
object[item] += 1;
})
// Now, every item of the input array has been counted in object.
// For each item of object:
for (var prop in object) {
// If it has been counted more than one time, add it to the result.
if(object[prop] >= 2) {
result.push(prop);
}
}
// Return the result.
return result;
}
console.log(find_duplicate_in_array([1, 2, -2, 4, 5, 4, 7, 8, 7, 7, 71, 3, 6]));
这里的复杂性是在那些线上:
if(!object[item])
object[item] = 0;
object[item] += 1;
它与更严格的表示法相同:
if(!object[item]) {
object[item] = 0;
}
object[item] += 1;
如果不设置花括号,则只执行下一条指令!
关于javascript - 这段代码如何在数组中搜索多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53349545/