简体   繁体   English

为什么我的for循环只出现一次?

[英]Why does my for loop only appear to run once?

This is one of freecodecamps challenges it passes the for loop inside the filter passes the first element of the array newArg but doesn't for the second one and so on therefore the challenge doesn't pass can someone explain to me why. 这是一个freecodecamps挑战,它通过过滤器内部的for循环传递数组newArg的第一个元素,但不是第二个元素,因此挑战没有通过可以有人向我解释原因。 Please don't write any full solutions as i just want a little help to move forward. 请不要写任何完整的解决方案,因为我只是想要一点帮助继续前进。

function destroyer(arr) {
  // Remove all the values
  var newArg = [];
  for (var i=1; i < arguments.length; i++){
         newArg.push(arguments[i]);
       }


 var newArray = arr.filter(function(val){
  for (i = 0; i < newArg.length; i++) {
     return val !== newArg[i];
  } 


 });
 return newArray;



}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

The filter call: filter调用:

var newArray = arr.filter(function(val){
  for (i = 0; i < newArg.length; i++) {
     return val !== newArg[i];
  } 
});

is the same as: 是相同的:

var newArray = arr.filter(function(val) {
  return val !== newArg[0];
});

because you are returning from the very first iteration. 因为你是从第一次迭代中返回的。

Solution: 解:

You'll have to wrap the return statement in an if like this: 你必须将return语句包装在if如下所示:

var newArray = arr.filter(function(val){
  for (i = 0; i < newArg.length; i++) {
     if(val === newArg[i]) { // don't return if val !== newArg[i]
       return true;          // return only when they're ===
     }
  }
  return false;              // default return (nothing is found in the array)
});

Or use an alternative such as Array.prototype.some like this: 或者使用像Array.prototype.some这样的替代方法:

var newArray = arr.filter(function(val){
  return newArg.some(function(arg) { // return true if some item pass the test (false otherwise)
     return arg === val;             // the test
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM