2017-01-11 5 views
0

文字列の結果をキー/値形式のプロパティの値として数えたオブジェクトに生成する関数があります。結果を文字列に反復してオブジェクト内に挿入する

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; 
} 
+1

ループ本体: 'obj [arr [i]] = obj [arr [i]] || 0; obj [arr [i]] ++;' – dandavis

+0

ありがとう!良いポインタのように思える...私はそれをチェックしてみましょう... –

答えて

0

は、あなたは自分の言葉で各文字を反復処理し、どちらかあなたのオブジェクトに新しいキーを追加、または既存のキーをインクリメントする必要があります

0

簡体コード:

var output = countAllCharsIntoObject('banana'); 
 
console.log(output); // --> {b: 1, a: 3, n: 2} 
 

 
function countAllCharsIntoObject(str) { 
 

 
    var arr = str; 
 
    var obj = {}; 
 
    for (var i = 0; i < arr.length; i++) { 
 

 
    obj[arr[i]] = obj[arr[i]] + 1 || 1 
 
    } 
 
    return obj; 
 
}

関連する問題