我正在努力检查arry是否包含值。
HTML:
var newprodata = [];
var alreadyUsedIds = [];
angular.forEach(prodata, function(line) {
if(line.name === proName || line.brand === proBrand){
//if (line.id === 183) {
var id = parseInt(line.id);
console.log("line.id",id);
console.log("alreadyUsedIds",alreadyUsedIds);
console.log( "alreadyUsedIds.indexOf("+id+")", alreadyUsedIds.indexOf(id) );
//}
if (alreadyUsedIds.indexOf(id) > -1){
console.log("on record pas");
} else {
//console.log("line.id",line.id);
console.log("on record");
alreadyUsedIds.push(parseInt(id));
newprodata.push(line);
}
}
});
这是我的控制台output
:
alreadyUsedIds [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
0: 24
1: 25
2: 26
3: 27
4: 28
5: 29
6: 30
7: 31
8: 32
9: 33
10: 34
11: 35
12: 36
13: 183
length: 14__proto__: Array[0] filters.js:46
alreadyUsedIds.indexOf(183) -1
,它不应该是' -1'因为' 183'在阵列中!!!
此外,如果我设置断点,并手动检查我得到:alreadyUsedIds.indexOf(183)= 13
答案 0 :(得分:1)
您使用alreadyUsedIds = [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
但是,此数组不包含元素183
,因此您不会在那里找到它
有关其工作原理的示例:
var alreadyUsedIds = [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36];
// returns -1, because there is no element 183
console.log( alreadyUsedIds.indexOf(183) )
// add 183 to the end of the array
alreadyUsedIds.push(183)
// returns 13, because the element 183 is at position 13
console.log( alreadyUsedIds.indexOf(183) )

答案 1 :(得分:0)
如果alreadyUsedIds实际上包含183,它可以正常工作,在jsfiddle演示:
https://jsfiddle.net/5qknqgex/
var alreadyUsedIds = [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 183];
console.log(alreadyUsedIds.indexOf(183));
唯一的解释是你的数组在console.log
时不包含183答案 2 :(得分:-1)
它在这里工作
https://jsfiddle.net/jtc2wppu/2/
var alreadyUsedIds = [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 183];
console.log(alreadyUsedIds.indexOf(183));