我是一个全新的这个所以如果我没有解释的问题,我应该,请让我知道!
基本上,我使用Twilio Quest作为开始学习Javascript的一种方式,但我自己有点卡住了。
挑战是测试一个字符串数组的条件,并在每次出现某个字符串时增加一个变量的值。。。然后在函数末尾返回所说变量的值。
以下是我所得到的:
let freightItems = ['contraband', 'clear', 'contraband', 'clear'];
freightItems.forEach(scan);
function scan(freightItems) {
const contrabandCount = 0;
if (freightItems.element == 'contraband') {
contrabandCount + 1;
}
return contrabandCount;
}
当我将代码提交给TwilioQuest时,我得到的错误是:
函数返回了一个数字,但不是我们要查找的值。 您的函数应该检查输入数组中的每一项,并返回字符串“违禁品”出现的总次数。
代码中有几个问题:
>
您应该在scan
函数中迭代数组,因为您无法像您尝试的那样返回contrabandCount
变量。 在scan
函数中移动foreach
循环
更改
contrabandCount + 1;
至
contrabandCount = contrabandCount + 1;
因为您需要使用contrabandCount+1
的结果更新contrabandCount
变量
null
let freightItems = ['contraband', 'clear', 'contraband', 'clear'];
function scan(freightItems) {
let contrabandCount = 0;
freightItems.forEach(str => {
if (str === 'contraband') {
contrabandCount = contrabandCount + 1;
}
})
return contrabandCount;
}
console.log(scan(freightItems))
这可能是一个解决方案
null
let contrabandCount = 0;
let freightItems = ['contraband', 'clear', 'contraband', 'clear'];
freightItems.forEach(el => {
if (el === 'contraband') {
contrabandCount++;
}
});
console.log(contrabandCount);
Foreach方法您可以使用此方法
null
let freightItems = ['contraband', 'clear', 'contraband', 'clear'];
let contrabandCount = 0;
freightItems.forEach(scan);
function scan(freightItem) {
freightItem == 'contraband' ? contrabandCount++ :contrabandCount;
}
console.log(contrabandCount)