仮定
const words = ["hello", "this", "is", "hello", "this", "anything"]
let wordcount = {};
words.forEach((w) => {
if (wordcount[w]) {
wordcount.w = wordcount.w++;
} else {
wordcount.w = 1;
}
})
console.log(wordcount)
期待される出力は次のようになります
{hello:2,this:2,is:1,anything:1}
代わりに、私はこれを受け取ります-
{w:1}
なぜ値ではなくプロパティとして追加されるのですか。
1
これは本当に不明確です。さらに情報を追加してください。何を達成しようとしていますか?あなたが直面している問題は何ですか?取得した出力を表示します...
– カラン クマール
2020 年 9 月 3 日 11:44
これは JavaScript の予約キーワードです。これについては別のアプローチが必要かもしれません。
– elpmid
2020 年 9 月 3 日 11:44
定義されているワードカウントを表示してください。
– ドヴィッドワイズ
2020 年 9 月 3 日 11:44
どこでも .w の代わりに [w] を使用してください
– ムプルジャン
2020 年 9 月 3 日 11:53
@dovidweisz: 投稿にあります let wordcount = {};。
– レイン
2020 年 9 月 3 日 11:53
------------------------
let y="test";
//While you use data.y then it means you create or update attribute with key y
var data={};
data.y=5;
console.log(data);
//While you use data[y] it means you create or update attribute with key as value of y
data[y]=2;
console.log(data);
つまり、wordcount.w ではなく wordcount[w] を使用します
words=["hello","this","is","hello","this","anything"]
let wordcount={};
words.forEach((w)=>{
if(wordcount[w])
{
wordcount[w]++;
}
else{
wordcount[w]=1;
}
})
console.log(wordcount)
------------------------
これを使用します:
let words = ["hello", "this", "is", "hello", "this", "anything"];
let wordCount = {};
words.forEach(w => {
if (wordCount[w] == undefined) wordCount[w] = 1;
else wordCount[w]++;
})
console.log(wordCount)
2020 年 9 月 3 日 11:53 に回答
0塩水
0塩水
470
5
銀バッジ 5 個
20
銅バッジ 20 個
2
1
同様にできます最後まで進みます: wordCount[w] = ~~wordCount[w] + 1。
– レイン
2020 年 9 月 3 日 11:55
if (wordCount[w] == unknown) は if (!wordCount[w]) と同じ効果があります
– ムプルジャン
2020 年 9 月 3 日 11:55