[英]Javascript Object Iteration with for loop
我正在嘗試計算字符串中出現唯一字符的次數。 但是我陷入對象迭代中,無論同一個字符出現多次,它只會返回1:
function allUniqueCha(word) { var wordObj = {}; var wordArray = word.split([, ]); wordArray.forEach(function(c) { wordObj[c] = +1; }); console.log(wordArray); console.log(wordObj); } allUniqueCha("Bubble")
輸出為:{B:1,u:1,b:1,l:1,e:1},但鍵“ b”的期望值應為2。
你寫了:
wordObj[c]=+1;
使用某些格式:
wordObj[c] = +1;
您總是將+1
分配給該值,此處沒有增量。 嘗試
wordObj[c] = (wordObj[c] || 0)+1;
和
var wordArray = word.split([, ]);
應該是
var wordArray = word.split("");
function allUniqueCha(word) { var wordObj = {}; var wordArray = word.split(""); wordArray.forEach(function(c) { wordObj[c] = (wordObj[c] || 0) +1; }); console.log(wordArray); console.log(wordObj); } allUniqueCha("Bubble")
當您這樣做時:
wordObj[c] = +1;
您正在將值+1
分配給屬性。 您要做的是將值增加1,因此:
wordObj[c] += 1;
但是,最初wordObj[c]
不存在,因此您嘗試遞增undefined ,這將引發錯誤。 因此,您必須測試該屬性是否存在,如果不存在,請對其進行初始化。
function allUniqueCha(word) { var wordObj = {}; var wordArray = word.split([, ]); wordArray.forEach(function(c) { if (!wordObj.hasOwnProperty(c)){ wordObj[c] = 0; } wordObj[c] += 1; }); console.log(wordArray); console.log(wordObj); } allUniqueCha("Bubble")
您還可以使用reduce :
function allUniqueCha(word) { return word.split('').reduce(function(acc, c) { acc[c] = (acc[c] || 0) + 1; return acc; },{}); } console.log(allUniqueCha("Bubble"));
在您最初的帖子中,這頭小豬背對了思路。 這是解決您正在尋找的問題的一種方法。
function allUniqueCha(word){
let wordArray = word.split([,]);
return wordArray.reduce((result, element) => {
result[element] = result[element] + 1 || 1;
return result;
}, {})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.