let specificSuffix = function(words, suffix) {
if (!Array.isArray(words)) {
return [];
}
return words.filter(function(word){
return word.endsWith(suffix)
});
}
console.log(specificSuffix(['family', 'hound', 'catalyst', 'fly', 'timidly', 'bond'], 'ly'));
// [ 'family', 'fly', 'timidly' ]
console.log(specificSuffix(['simplicity', 'computer', 'felicity'], 'ily'));
// [ ]
我特別困惑:
return words.filter(function(word) {
return word.endsWith(suffix)
});
}
我如何退回這兩個東西?過濾器在說,回傳這個空的新陣列,用 endWith 后綴的詞填充它......(我認為)
真正讓我失望的只是兩個回報。這是如何運作的?
uj5u.com熱心網友回復:
return words.filter(function(word){
return word.endsWith(suffix)
});
外部回傳回傳的結果words.filter()
。在filter()
函式內部,我們必須傳遞一個回呼。所以return
里面是那個回呼。簡而言之,您必須根據過濾器回呼中的條件回傳真/假。
uj5u.com熱心網友回復:
當代碼的縮進做得這么糟糕的時候,出現這種混亂是很正常的……
具有正確縮進的相同代碼:
let specificSuffix = function(words, suffix) {
if (!Array.isArray(words)) {
return [];
}
return words.filter( function(word) {
return word.endsWith(suffix)
});
}
或具有箭頭功能的相同代碼
function specificSuffix(words, suffix)
{
if (!Array.isArray(words)) return [];
return words.filter( word => word.endsWith(suffix) )
}
uj5u.com熱心網友回復:
也許如果我們提取變數result
代碼會更有意義?
const specificSuffix = function(words, suffix) {
if (!Array.isArray(words)) return [];
const result = words.filter(function(word) {
return word.endsWith(suffix)
});
return result;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/430614.html
標籤:javascript 数组 方法 筛选 布尔表达式