如何返回包含不匹配JavaScript中给定参数的元素的数组?

时间:2021-12-24 16:52:58

Write a function called "removeElement".

编写一个名为“removeElement”的函数。

Given an array of elements, and a "discarder" parameter, "removeElement" returns an array containing the items in the given array that do not match the "discarder" parameter.

给定一个元素数组和一个“丢弃器”参数,“removeElement”返回一个数组,该数组包含给定数组中与“丢弃器”参数不匹配的项。

Notes: * If all the elements match, it should return an empty array. * If an empty array is passed in, it should return an empty array.

注释:*如果所有元素匹配,则返回一个空数组。*如果传入一个空数组,它应该返回一个空数组。

I thought this would be the solution:

我想这就是解决办法:

  function removeElement(array, discarder) {

    var newarr = array.filter(function(cv, i, a){
      if (array == []) {
        return [];
      } else if (cv != discarder ) {
        return  cv;
      } 
    });
      return newarr;
  }

But I get this error:

但是我得到了这个错误:

return_an_array_with_all_booleans_not_matching_discarder return an array with all booleans not matching discarder

return_an_array_with_all_booleans_not_matching_der返回一个带有所有布尔值的数组,而不是匹配丢弃器。

I thought this would then work, because initially I didn't add the clause to factor in if all values were equal to discarder.

我认为这样做是可行的,因为最初我没有在所有值都等于丢弃时添加子句。

function removeElement(array, discarder) {

    var newarr = array.filter(function(cv, i, a){
      if ((array == []) || (cv == discarder)) { // added this expression to evaluate.
        return [];
      } else if (cv != discarder ) {
        return  cv;
      } 
    });
      return newarr;
  }

1 个解决方案

#1


4  

While Array#filter

而数组#过滤器

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

filter()方法创建一个新的数组,其中包含通过提供的函数实现的测试的所有元素。

needs a boolean (or at least a truthy/falsy) value to return, you could just return the check with the given discarder and return the comparison result.

需要返回一个布尔值(或至少一个truthy/falsy),您只需返回给定丢弃器的检查并返回比较结果。

The result is an array without the given value.

结果是一个没有给定值的数组。

function removeElement(array, discarder) {
    return array.filter(function(value) {
        return value !== discarder;
    });
}

#1


4  

While Array#filter

而数组#过滤器

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

filter()方法创建一个新的数组,其中包含通过提供的函数实现的测试的所有元素。

needs a boolean (or at least a truthy/falsy) value to return, you could just return the check with the given discarder and return the comparison result.

需要返回一个布尔值(或至少一个truthy/falsy),您只需返回给定丢弃器的检查并返回比较结果。

The result is an array without the given value.

结果是一个没有给定值的数组。

function removeElement(array, discarder) {
    return array.filter(function(value) {
        return value !== discarder;
    });
}