[英]having trouble targeting element of an array instead of it's position using a for loop
When running this function I keep getting back an array that just returns the first parameter (a). 运行此函数时,我会不断返回一个仅返回第一个参数(a)的数组。 The ultimate goal is to return an array that finds any match to the second parameter (b) and remove it from the first parameter. 最终目标是返回一个找到与第二个参数(b)匹配的数组并将其从第一个参数中删除。 I've included two test functions below. 我在下面包括了两个测试功能。 I've been working on it for a while and it seems like it's just ignoring the condition in my 'if' statement. 我已经研究了一段时间了,似乎只是在忽略我的“ if”语句中的条件。 Can anyone spot why? 谁能找到原因? I'm also open to cleaner ways to do this, as I'm still learning JavaScript. 我仍在学习更清洁的方法来做到这一点,因为我仍在学习JavaScript。 Thanks in advance! 提前致谢!
function array_diff(a, b) {
var newArr = [];
for ( i = 0; i < a.length; i++) {
if (b !== a[i]) {
newArr.push(a[i]);
}
}
return newArr;
}
array_diff([1,2,2,2,3],[2]);
array_diff([1,2],[1]);
The problem is that you're comparing an array to a value. 问题在于您正在将数组与值进行比较。
Because a[i]
is a value, b
should also be value and not an array so try 因为a[i]
是一个值,所以b
也应该是value而不是数组,因此请尝试
array_diff([1,2,2,2,3],2);
array_diff([1,2],1);
ie 2
instead of [2]
and 1
instead of [1]
即2
代替[2]
和1
代替[1]
Another way is to change your if condition 另一种方法是更改您的if条件
if (b[0] !== a[i]) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.