首页 > 解决方案 > TwilioQuest Javascript 实验室持续警惕

问题描述

目标:这个函数应该接受一个参数——一个字符串数组。您的扫描函数必须遍历该数组中的所有字符串,并使用布尔逻辑检查每个字符串。

如果输入数组中的字符串等于违禁品值,则将该项目的索引添加到输出数组。当你扫描完整个输入数组后,返回输出数组,它应该包含数组中所有可疑项目的索引。

例如,给定一个输入数组:

['contraband', 'apples', 'cats', 'contraband', 'contraband'] 你的函数应该返回数组:

[0, 3, 4] 此列表包含输入数组中所有违禁品字符串的位置。

我的代码:

function scan(freightItems) {
  let contrabandIndexes = [];

  freightItems.forEach(el => {
    console.log(freightItems.indexOf(el, 0));
    if (el == "contraband") {
      contrabandIndexes.push(freightItems.indexOf(el, 0));
    }
  });
  return contrabandIndexes;
}

const indexes = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Contraband Indexes: ' + indexes); // should be [1, 4]

我无法弄清楚为什么第二个“违禁品”的指数又回到了 1,以及为什么我在 TwilioQuest 中没有超过这个水平。任何帮助表示赞赏。

标签: javascriptarraystwilio

解决方案


尝试这样的事情:

function scan(freightItems) {
  let contrabandIndexes = [];

  freightItems.forEach((el, idx) => {
    if (el == 'contraband') {
      contrabandIndexes.push(idx);
    }
  });
  return contrabandIndexes;
}

const indexes = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Contraband Indexes: ' + indexes); // should be [1, 4]

indexOf用于搜索数组:

indexOf() 方法返回可以在数组中找到给定元素的第一个索引

但是el是数组中的一个项目。


推荐阅读