javascript - 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 中没有超过这个水平。任何帮助表示赞赏。
解决方案
尝试这样的事情:
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
是数组中的一个项目。
推荐阅读
- c# - C# 有效读取流内容并限制读取量
- node.js - 如何使用 multer 检查上传文件的文件大小
- python - 如何使用pyqt4删除表格小部件中的特定行边框
- javascript - 当我在幻灯片中按下一个 div 时,如何更改另一个 div 的内容?
- header - 如何在 prestashop 中更改标题的名称
- doc2vec - 处理 doc2vec 培训中的附加信息
- vue.js - Vue slideToggle不流畅
- c++ - 在另一个类的构造函数的成员初始化程序中声明的类在它之外是否可见?
- python - 在fortran代码的python回调例程中传递动态参数
- django - 尝试从 aurelia js 文件进行 django api 调用时出现禁止错误