-1

O'Reilly の JS Definitive Guide を読んで、次のコード ブロックに出くわしました。

let freq = {};
for (let item of "alabama") {
   if (freq[item]) {
     freq[item]++;
  } else {
     freq[item] = 1; 
 } 
}

構文と意味のいくつかを調べたいだけです。

  1. 空のオブジェクトを「freq」変数に代入する
  2. 指定された文字列に対して for/of ループを実行する
  3. if ステートメントは、freq[item] が true を返すかどうかをチェックします..その部分は取得できますが、その真の値をトリガーするものは何ですか?
  4. では、どのようにして偽の値がトリガーされ、値が 1 になるのでしょうか?

少し早いですがお礼を!

4

3 に答える 3

0

First, keep in mind that when iterating over a string with for..of, the item declared for each loop (which you've named item) is each character of the string.

Since the object starts out empty, freq[item] will initially be undefined. For example, on the first iteration, {}['a'] is undefined, which is falsey, so the else is entered:

freq['a'] = 1; 

On subsequent iterations, when the character a is found, the a property will exist on the object, so the if is entered, incrementing that property value:

freq['a']++;
于 2020-09-08T03:24:22.817 に答える
0

The first time you find a letter not in the object it will return undefined

1) a
    freq['a'] will be undefined 
    therefore the code will set a 1 to it 
    freq['a'] = 1
2) l will go through the same steps as #1
3) a 
    freq['a'] will be 1 
    so it's truthy therfore we add 1 to it 
    freg['a'] ++; which will make it 2

Then you can follow same pattern to figure out the rest

于 2020-09-08T03:24:27.947 に答える