這是我的第一篇文章,大約幾周前開始學習 js,大約 8 小時!我知道一個非常相似的問題有一個很好的答案,但我試圖理解為什么我做錯了。
目標:這個函式應該接受一個引數——一個字串陣列。您的掃描函式必須遍歷該陣列中的所有字串,并使用布爾邏輯檢查每個字串。
如果輸入陣列中的字串等于違禁品值,則將該專案的索引添加到輸出陣列。當你掃描完整個輸入陣列后,回傳輸出陣列,它應該包含陣列中所有可疑專案的索引。
例如,給定一個輸入陣列:
['contraband', 'apples', 'cats', 'contraband', 'contraband'] 你的函式應該回傳陣列:
[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]
當我應該得到“Contraband Indexes 1, 4”時,我一直得到輸出“Conrtraband Indexes:”
請幫忙!
uj5u.com熱心網友回復:
你的代碼中有一個錯字。我認為應該是
...
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 ...在)
uj5u.com熱心網友回復:
下面的代碼使用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]
輸出:'違禁品索引: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]
輸出:'違禁品索引:1,4'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462022.html
標籤:javascript 数组 循环 暮光之城
