简体   繁体   English

使用for循环定位数组元素而不是其位置时遇到麻烦

[英]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.

相关问题 使用MaterliazeCSS并尝试将按钮固定在其父元素内的固定位置,但遇到麻烦 - Using MaterliazeCSS and trying have a button in a fixed position inside it's parent element but having trouble 无法返回数组的元素 - Having trouble returning an element of an array 定位选择器(或其他东西)时遇到问题 - Having trouble targeting a selector (or something) 循环数组返回字符串类型的元素,而不是数组的类型 - Loop array returns element of type string instead of array's type 在 for 循环中访问比当前索引少或多一个索引的数组元素时遇到问题(即使它存在) - Having trouble accessing an element of an array that is one index less or greater than current index in a for loop(even though it exists) 在iFrame中定位元素时遇到问题 - Having trouble targeting elements inside an iFrame 无法定位按键来完成操作 - Having trouble targeting key presses to complete an action 在更改数组位置和以角度动态显示内容时遇到麻烦 - Having trouble with changing an array position and displaying contents dynamically with angular 在创建新的对象数组时遇到麻烦(在循环内部循环) - Having trouble creating a new array of objects in angular (loop inside of loop) 在空数组上使用 setState 时遇到问题 - Having trouble using setState on an empty array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM