2016-11-12 4 views
1

は、引数として文字列が与えられたとき、キーは文字列内の単語があるオブジェクトを返す関数countWords書き込み、および値は、文字列内のその単語の出現回数である:この条件でこのオブジェクトキーにアクセスするにはどうすればよいですか?

function countWords(string){ 
    string = string.split(" "); 
    var newObj = {}; 
    for(var i = 0 ; i === newObj.string ; i++){ 
     if(newObj['i'] === newObj[string]){ 
      newObj[string[i]] = i ; 
     } 
    } 
     return newObj; 
    } 
countWords("hello hello"); // => {"hello": 2} 
countWords("Hello hello"); // => {"Hello": 1, "hello": 1} 
countWords("The quick brown"); // => {"The": 1, "quick": 1, "brown": 1} 

I分割された文字列のインデックスを数える必要がないので、i < string.lengthからi === key value of of the objectsに条件を変更する必要があります。 newObj.stringで文字列にアクセスできないのはなぜですか?

+0

'newObj.string'はまだ性質を持っていない、新たに定義された空のオブジェクトに意味がありません。あなたはそれを変更する必要があるアイデアがどこから来るかわからない配列の長さを使用したい – charlietfl

答えて

1

forループの代わりにreduce()とすることができます。

function countWords(string) { 
 
    return string.split(' ').reduce(function(r, e) { 
 
    r[e] = (r[e] || 0) + 1; 
 
    return r; 
 
    }, {}) 
 
} 
 
console.log(countWords("hello hello")) 
 
console.log(countWords("Hello hello")) 
 
console.log(countWords("The quick brown"))

ループ forであなたのコードは次のように行くことができます。

function countWords(string) { 
 
    var string = string.split(" "); 
 
    var newObj = {}; 
 

 
    for (var i = 0; i < string.length; i++) { 
 
    newObj[string[i]] = (newObj[string[i]] || 0) + 1 
 
    } 
 
    return newObj; 
 
} 
 
console.log(countWords("hello hello")); 
 
console.log(countWords("Hello hello")); 
 
console.log(countWords("The quick brown"));

+0

はい私は前にこの答えを見た、ありがとう。しかし、私は減らすために移動する前に、forループでそれを解決する方法を知りたいです – heliu

+0

ありがとうございます!私は一種のもので、string.lengthを変更する必要はなかったと思います。もう1つの質問.. newObj [string [i]] =(newObj [string]] || 0)+ 1 これは三項演算子と呼ばれるものですか?真実と虚偽の価値を持っていますか? – heliu

+0

あなたは歓迎です、それは三元演算子ではありませんこれは '(条件)ですか? true:false'で、各キーのデフォルト値を0に設定するだけです。 –

0

function countWords(string){ 
 
    return string 
 
    .split(" ") 
 
    .reduce((acc, curr) => { 
 
     if (curr in acc) { 
 
     acc[curr]++ 
 
     } else { 
 
     acc[curr] = 1 
 
     } 
 
     return acc 
 
    }, {}) 
 
} 
 
console.log(countWords("hello hello")); 
 
console.log(countWords("Hello hello")); 
 
console.log(countWords("The quick brown"));

0

それが増加しない場合は、プロパティは、JavaScriptのオブジェクトに存在するかどうかをチェックするためにhasOwnProperty機能を使って、次のようにそれを行うことができますそのカウントを1に初期化します。

function countWords(data) { 
 
    var words = data.split(" "); 
 
    var item = {}; 
 
    for (var i = 0; i < words.length; i++) { 
 
    var prop = words[i]; 
 
    item.hasOwnProperty(prop) ? item[prop] ++ : item[prop] = 1; 
 
    } 
 

 
    console.log(item); 
 
    return item; 
 
} 
 

 
countWords("hello hello"); // => {"hello": 2} 
 
countWords("Hello hello"); // => {"Hello": 1, "hello": 1} 
 
countWords("The quick brown"); // => {"The": 1, "quick": 1, "brown": 1}

関連する問題