我有一个关于JS数组的问题.
例:
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
Run Code Online (Sandbox Code Playgroud)
我们有一个主数组fullArr和一个部分数组partarr.我想创建一个函数/过滤器,它正在寻找现有的项目fullArr而不是partArr.在这个例子中,上面newArr必须等于[1,4].
我尝试过做这样的事情,但它没有正常工作.
for (var k in fullArray) { // [1,2,3,4]
for (var j in selectedArray) { // [1,4]
if (fullArray[k] == selectedArray[j]) {
newArray.splice(selectedArray[j] - 1, 1); // must be [2,3]
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
制作这个的好方法是什么?谢谢.
这是一个
var newArr = fullArr.filter(function(f) { // The filter() method creates a new array with all elements that pass the test implemented by the provided function.
return partArr.indexOf(f) == -1; // The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
})
Run Code Online (Sandbox Code Playgroud)
给女孩留下深刻印象,你也可以
var newArr = fullArr.filter(function(f) {
return !~partArr.indexOf(f);
})
Run Code Online (Sandbox Code Playgroud)