TwilioQuest Javascript 问题:时刻保持警惕

TwilioQuest Javascript Problem: Constant Vigilance

这是我的第一个 post,大约几周前开始学习 js,大约 8 个小时!我知道一个非常相似的问题有一个很好的答案,但我试图理解为什么我所做的是错误的。

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

如果输入数组中的字符串等于值 contraband,则将该项目的索引添加到输出数组。扫描完整个输入数组后,return 输出数组,其中应包含数组中所有可疑项的索引。

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

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

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

function scan(freightItems) {
let contrabandIndexes = [];
  for (let index in freightItems)
  if (freightItems == 'contraband') contrabandIndexes.push(index);

return contrabandIndexes;
}

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

当我应该得到“违禁品索引 1、4”时,我一直得到输出“Conrtraband Indexes:”

请帮忙!

你的代码有错别字。我想应该是

...
for (let index in freightItems) 
if (freightItems[index] == 'contraband') // comparison of a value taken by index over comparing the whole array 
...

请注意,for...in 循环不是数组迭代的首选( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#array_iteration_and_for...in )

下面的代码使用了forEach.

function scan(freightItems) {
  let contrabandIndexes = [];
  freightItems.forEach((element, index) => {
    if (element == 'contraband') contrabandIndexes.push(index);
  })
return contrabandIndexes;
}

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

输出: 'Contraband Indexes: 1,4'

或者通过一些更改修改您的代码

function scan(freightItems) {
let contrabandIndexes = [];
  for (let index in freightItems) {
    if (freightItems[index] == 'contraband') contrabandIndexes.push(index);
  }

return contrabandIndexes;
}

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

输出:'Contraband Indexes: 1,4'