如何迭代数组,每次迭代都采用前一个结果?我正在数组 B 中寻找与数组 A 中相同的值,但数组 A 只有一个值,例如 for in 循环的结果。我想要返回数组 C,它是从数组 A 中的所有项目中减去起始数组。
到目前为止我有这个代码:
x = newArray.indexOf(zeme[0]);
for (b = 0; b < newArray.length; b++) {
if (x === b) {
newArray.splice(b, zeme.length);
}
}
带有值:
array B = ['can', 'usa', 'eng'];
array A = ['eng'];
array A = ['can'];
获取结果:
array C = ['can', 'usa']
//first iteration, found 'eng' and deleted.
array C = ['usa', 'eng']
//second iteration found 'can' and deleted.
所需结果:
array C = ['usa']
//after first iteration in array left only two items ['can', 'usa']
//after second iteration take array ['can', 'usa'] and splice 'can'
最佳答案
如果
I want return array C which is starting array substracted of all items in array A.
是你问题的要点,听起来你想要数组交集。
function intersect(a, b) {
return a.filter((v) => b.indexOf(v) === -1);
}
console.log(intersect(['can', 'usa', 'eng'], ['usa', 'eng']));
输出
['can']
(注意:上述实现并未优化;对于大型 b
数组,它可能会变得非常慢,因为最坏情况的复杂度为 O(n^2)。)
关于javascript - 每次迭代都从之前的迭代结果开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52705800/