我正在尝试在数组中找到一个元素。这是小提琴:
var selectedVals = [630, 85];
var registeredVals = [17, 630, 85];
var newList = [];
$(selectedVals).each(function () {
//registeredVals.splice($.inArray(this, registeredVals), 1);
var num = this;
alert("Value="+ num + " Array=" + registeredVals);
//alert(registeredVals.indexOf(num));
alert($.inArray(this, registeredVals));
if($.inArray(this, registeredVals) == -1)
newList.push(this);
})
https://jsfiddle.net/programmedprojects/7m9zrjwL/
我尝试使用.indexOf和$ .inArray来查找循环中的元素。
当元素在数组中时,索引是否应该大于-1?
答案 0 :(得分:1)
如果您想知道selectedVals
和registeredVals
上的元素,可以使用filter()
并使用includes()
来检查数组中是否存在变量。
var selectedVals = [630, 85, 99];
var registeredVals = [17, 630, 85];
var newList = selectedVals.filter(o => registeredVals.includes(o));
console.log(newList);
没有ES6
var selectedVals = [630, 85, 99];
var registeredVals = [17, 630, 85];
var newList = [];
for (var i = 0; i < selectedVals.length; i++) {
if (registeredVals.indexOf(selectedVals[i]) !== -1) newList.push(selectedVals[i]);
}
console.log(newList);