[英]How to use an arrow function inside an Array.map() function with react
[英]Arrow function VS normal function in Array.map()
我正在解決一些JS挑戰,並注意到當使用箭頭功能時,結果如預期的那樣,當我使用正常功能嘗試相同的代碼時卻沒有。 有人可以解釋差異,否則我可能有錯字!!
這是第一個解決方案(有效):
function titleCase(str) {
str = str.split(' ').map(i => i[0].toUpperCase() + i.substr(1).toLowerCase()).join(' ')
return str;
}
console.log(titleCase("I'm a liTTle tea pot")); // I'm A Little Tea Pot
第二種具有正常功能的解決方案(返回空字符串):
function titleCase2(str) {
str = str.split(' ').map(function(i, index){ i[0].toUpperCase() + i.substr(1).toLowerCase()}).join(' ')
return str;
}
console.log(titleCase2("I'm a liTTle tea pot")); // empty string
您會在回調函數中錯過return
關鍵字。
Fat-arrow函數默認情況下返回值, return
關鍵字是內置的。 要從普通函數表達式中獲取值,您必須將其返回。
function titleCase2(str) { str = str.split(' ').map(function(i, index) { return i[0].toUpperCase() + i.substr(1).toLowerCase() }).join(' ') return str; } console.log(titleCase2("I'm a liTTle tea pot"));
您需要顯式return
非箭頭函數。 1行箭頭功能隱式返回該行的結果。
function titleCase2(str) {
return str.split(' ').map(function(i, index){ return i[0].toUpperCase() + i.substr(1).toLowerCase()}).join(' ')
}
console.log(titleCase2("I'm a liTTle tea pot")); // I'm A Little Tea Pot
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.