【问题标题】:Javascript array compare function using filter - not working使用过滤器的 Javascript 数组比较函数 - 不起作用
【发布时间】:2023-01-11 03:43:10
【问题描述】:

我写了下面的代码来回答这个问题:

编写一个函数 justCoolStuff() 接受两个字符串数组,并使用内置的 .filter() 方法返回一个包含两个数组中都存在的项目的数组。

我想使用循环而不是 includes() 数组方法来解决这个问题。我在正确的轨道上吗?代码返回一个用空数组填充的空数组。

const justCoolStuff = (arrOne,arrTwo) => {
  const sharedWord = [];
  for (i = 0; i < arrOne.length; i++) {
    for (j = 0; j < arrTwo.length; j++) {
      sharedWord.push(arrOne.filter(arr => arrOne[i] === arrTwo[j]));
    }
  }
  return sharedWord;
};


const coolStuff = ['gameboys', 'skateboards', 'backwards hats', 'fruit-by-the-foot', 'pogs', 'my room', 'temporary tattoos'];

const myStuff = [ 'rules', 'fruit-by-the-foot', 'wedgies', 'sweaters', 'skateboards', 'family-night', 'my room', 'braces', 'the information superhighway']; 


console.log(justCoolStuff(myStuff, coolStuff))

// Should print [ 'fruit-by-the-foot', 'skateboards', 'my room' ]

另外,有没有办法使用回调函数正确编写它,使其更易于理解/可读?

【问题讨论】:

  • filter 返回一个数组,您将过滤器的结果推送到一个数组,因此嵌套数组。这个过滤器甚至没有任何意义,因为你没有使用 arr 变量
  • 欢迎来到堆栈溢出!这是您开始熟悉using a debugger 的好机会。当您在调试器中单步执行代码时,哪个操作首先会产生意外结果?该操作中使用的值是什么?结果如何?预期的结果是什么?为什么?要了解有关此社区的更多信息以及我们如何为您提供帮助,请从tour 开始并阅读How to Ask 及其链接资源。

标签: javascript arrays filter include


【解决方案1】:

你不在正确的轨道上。

const justCoolStuff = (arrOne,arrTwo) => {
  //  const sharedWord = []; //you don't need this
  return arrOne.filter(function(item) {
    // you need to return true if item is in arrTwo
    // there are a number of ways in which you could test for this, one being
    // using includes on arrTwo
  });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多