-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

在javascript中以下是错误的 "",false,0,undefined,null..在你的情况下freq是一个空对象

freq ={}

在循环的第一次迭代中

item = 'a'

freq[item]将是未定义的,如果 在其他情况下如此,freq[item]即。 第三次迭代 的第二次迭代相同的方式 falsefreq[item] = 1freq={a:1}freq={a:1,l:1}

item = 'a'

freq[item]will be 1 if freq[item]will be true and incrementsfreq={a:2,l:1}

于 2020-09-08T04:20:11.747 回答
0

首先,请记住,当使用 迭代字符串时for..of,为每个循环声明的项目(您已命名为item)是字符串的每个字符。

由于对象一开始是空的,freq[item]所以最初是undefined. 例如,在第一次迭代中,{}['a']isundefined是错误的,因此else输入的是:

freq['a'] = 1; 

在随后的迭代中,当a找到字符时,该a属性存在于对象上,因此if输入 ,增加该属性值:

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

第一次找到不在对象中的字母时,它将返回 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

然后你可以按照相同的模式找出其余的

于 2020-09-08T03:24:27.947 回答