[英]Javascript assign and increment Obj's key value(with Reduce)
我正在學習在線課程,其中一個挑戰是:
編寫一個名為元音計數的函數,它接受一個字符串並返回一個對象,每個鍵是元音,值是元音在字符串中出現的次數(對象中鍵的順序無關緊要)。
vowelCount('incredible');
// {i:2, e: 2}
vowelCount('awesome');
// {a:1, e:2, o:1}
到目前為止,我已經想出了以下代碼,使用 Javascript 的 reduce:
function vowelCount(word) {
var vowels = ['a', 'e', 'i', 'o', 'u'];
var final = word.split('').reduce(function(obj, val, index) {
if (vowels.indexOf(val) > -1) {
//obj[val] = 0
obj[val]++;
}
return obj
}, {})
console.log(final)
}
我想我已經接近了,但是在檢查元音鍵是否為元音時,我無法確定如何分配和增加元音鍵的數值。 我嘗試將該值實例化為 0,但這只會將該值保持為 1。
使用短路評估來檢查該值是否存在,如果不存在,則使用 0 代替:
console.log(vowelCount('incredible')); // {i:2, e: 2} console.log(vowelCount('awesome')); // {a:1, e:2, o:1} function vowelCount(word) { var vowels = ['a', 'e', 'i', 'o', 'u']; return word.split('').reduce(function(obj, val, index) { if (vowels.indexOf(val) > -1) { obj[val] = (obj[val] || 0) + 1; } return obj; }, {}); }
此外,您可以使用元音初始化結果對象,並直接增加它們,而不是使用元音數組和Array.indexOf()
檢查:
console.log(vowelCount('incredible')); // {i:2, e: 2} console.log(vowelCount('awesome')); // {a:1, e:2, o:1} function vowelCount(word) { return word.split('').reduce(function(obj, val) { if(val in obj) { obj[val]++; } return obj; }, { a: 0, e: 0, i: 0, o: 0, u: 0 }); }
我認為這實際上是 reduce 的一個糟糕用例。 可能只使用常規 for 循環並使用 or 運算符( ||
)將undefined
替換為0
:
function vowelCount(word){
const vowels = "aeiou";
const result = {};
for(const char of word)
if(vowels.includes(char))
result[char] = (result[char] || 0) + 1;
return result;
}
如果這太詭異了,你可以檢查結果中是否已經存在 char 並設置它:
function vowelCount(word){
const vowels = "aeiou";
const result = {};
for(const char of word){
if(vowels.includes(char)){
if(!result[char]) result[char] = 0;
result[char]++;
}
}
return result;
}
你非常接近! 那是因為你試圖增加 undefined。 在遞增之前,您必須將該值設置為等於累加器上的一個數字。
function vowelCount(word) {
var vowels = ['a', 'e', 'i', 'o', 'u'];
var final = word.split('').reduce(function(obj, val, index) {
if (vowels.indexOf(val) > -1) {
// if we have seen the vowel, we increment it. Otherwise, it is the first time.
obj[val] ? obj[val]++ : obj[val] = 1;
}
return obj
}, {})
console.log(final)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.