文字列の結果をキー/値形式のプロパティの値として数えたオブジェクトに生成する関数があります。結果を文字列に反復してオブジェクト内に挿入する
var output = countAllCharsIntoObject('banana');
console.log(output); // --> {b: 1, a: 3, n: 2}
私の問題は、文字列
function countAllCharsIntoObject(str){
var arr = str.split('');
var obj = {};
for(var i = 0; i < arr.length; i++) {
//how to iterate the arr[i] and assign the value of the chars to the
//keys/values of the new obj. And if more then 1 indexOf(arr[i]) then
//change through an iteration the value of the new char key.I tried so
//many solutions without effect.
}
return obj;
}
の配列のループの横だけのキー/値の代入とループ内のiが同時にループ事実のまわりで私の心を包むことができないということですループの結果(値の動的増分を伴う)。 ご協力いただければ幸いです! 普通のJSの中に...アンダースコアやロダッシュやjQueryのソリューションはありません。 ありがとう!
function countAllCharsInObject (word) {
var letterCounts = {};
var currentLetter;
for (var i = 0; i < word.length; i++) {
currentLetter = word[i];
if (currentLetter in letterCounts) {
letterCounts[currentLetter] += 1;
} else {
letterCounts[currentLetter] = 1;
}
}
return letterCounts;
}
ループ本体: 'obj [arr [i]] = obj [arr [i]] || 0; obj [arr [i]] ++;' – dandavis
ありがとう!良いポインタのように思える...私はそれをチェックしてみましょう... –