【问题标题】:Remove specific strings from an Array in JavaScript在 JavaScript 中从数组中删除特定字符串
【发布时间】:2018-05-15 02:30:22
【问题描述】:

我正在解决一个练习题,它有一个问题是在函数内部创建一个空数组并将字符串数组作为参数传递给函数并从中删除特定单词。

这是一个问题: 编写一个名为 removeAll 的函数,它接受一个字符串数组和一个字符串作为参数,并返回一个新数组。返回的数组应该等同于参数数组,但删除了所有出现的 String 参数,忽略大小写。作为函数调用的结果,数组参数应保持不变。例如,如果一个名为 words 的数组包含 ["foo", "bar", "baz", "Foo", "FOO"],removeAll(words, "foo") 的调用应该返回 ["bar", "巴兹”]。

我的代码:我越来越不确定

function removeAll(words, remove){
  let arr = [];
  remove = '';
  arr = arr.filter(words => words !== remove);
}

removeAll(["foo", "bar", "baz"], "foo");

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 你为什么将 remove 设置为 ''
  • 你应该过滤words,而不是arr
  • function removeAll(words, remove){ words = words.filter(word => word !== remove); }
  • 你没有返回任何东西......并且你的代码不处理案例

标签: javascript arrays string


【解决方案1】:

你接近了,但你有 2 个错误。不要将删除设置为''。并且过滤词不是arr

function removeAll(words, remove){
  return words.filter(word => word.toLowerCase() !== remove.toLowerCase());
}

【讨论】:

    【解决方案2】:

    您在内部以错误的方式使用变量。

    // toLowerCase to compare lowercase strings
    function removeAll(words, remove){
      return words.filter(word => 
        word.toLowerCase() !== remove.toLowerCase()
      );
    }
    
    console.log(removeAll(["foo", "bar", "baz", "FOO"], "foo"));
    
    
    // Using Arrow functions
    removeAllES6 = (words, remove) => 
       words.filter(word => word.toLowerCase() !== remove.toLowerCase())
    
    console.log(removeAllES6(["foo", "bar", "baz", "FOO"], "foo"));

    【讨论】:

      【解决方案3】:

      除了已经提到的,由于您需要不区分大小写的比较,请使用toLowerCase()toUpperCase()

      function removeAll(words, remove){
        return words.filter(words => words.toUpperCase() !== remove.toUpperCase());
      }
      
      arr = removeAll(["foo", "bar", "baz"], "foO");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 2021-08-21
        • 2018-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多