這是我的第一個問題,因為我剛接觸編碼。
我想使用 .map 從陣列中獲取字串。
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot']
let trueRoots = root_vegetables.map((roots) => {
if (roots == 'carrot' && 'sweet potato') {
return 'True Roots';
}
return 'Modified Roots';
})
console.log(trueRoots);
所以我的預期答案是。
['Modified Roots', 'Modified Roots', 'True Roots', 'True Roots']
有沒有辦法做到這一點?
uj5u.com熱心網友回復:
看起來您的 if 陳述句條件不正確。你正在做(roots == 'carrot' && 'sweet potato'),這不起作用,因為你需要在 AND 操作(&&)之后有另一個條件而不是一個值,因為它只會回傳 true(AND 之后的陳述句,而不是 if 條件)
因此,您可以更改roots == 'carrot' && 'sweet potato'為roots == 'carrot' || roots == 'sweet potato'. 請注意,我們的條件從 AND 變為 OR 條件。
但你也可以這樣做:
// We use the const keyword instead of let if we don't change the value
// We use true_roots array to do the checking
const true_roots = ['carrot', 'sweet potato']
const root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot']
// We loop through the root_vegetables array and for each value
// we check if its in the true_roots array using the .includes method
// If its included, we return 'True Roots'
// else return 'Modified Roots'
// The code inside the map function is just shorthand/syntactical sugar
const trueRoots = root_vegetables.map((roots) => (modified_roots.includes(roots) ? 'True Roots' : 'Modified Roots'))
console.log(trueRoots);
uj5u.com熱心網友回復:
這是你問的嗎。
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot']
let trueRoots = root_vegetables.map((roots) => {
if (roots == 'carrot' || roots =='sweet potato') {
return 'True Roots';
}
return 'Modified Roots';
})
console.log(trueRoots);
uj5u.com熱心網友回復:
保持你的代碼幾乎相同,你也可以這樣做:
let root_vegetables = ['potato', 'taro', 'sweet potato', 'carrot']
var roots = [];
for (var i = 0; i < root_vegetables.length; i ) {
roots[i] = 'Modified Roots';
if (root_vegetables[i] == 'carrot' || root_vegetables[i] == 'sweet potato') {
roots[i] = 'True Roots'
}
}
console.log(roots)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/460663.html
標籤:javascript 数组 细绳
