3 回答
TA贡献1995条经验 获得超2个赞
首先,请记住,在使用 迭代字符串时for..of,为每个循环声明的项目(您已命名为item)是字符串的每个字符。
由于该对象一开始是空的,freq[item]因此最初是undefined. 例如,在第一次迭代中,{}['a']isundefined是假的,因此else输入:
freq['a'] = 1;
a在随后的迭代中,当找到该字符时,该a属性将存在于对象上,因此if输入 ,增加该属性值:
freq['a']++;
TA贡献1898条经验 获得超8个赞
第一次发现不在对象中的字母时,它将返回 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
然后你可以按照相同的模式找出其余的
TA贡献1828条经验 获得超3个赞
在 javascript 中以下是错误的 "",false,0,undefined,null..在你的情况下 freq 是一个空对象
freq ={}在循环的第一次迭代中
item = 'a'
freq[item]freq[item]如果在 else 中是false 这样,则将是未定义的freq[item] = 1。 第二次迭代第三次迭代freq={a:1} 的方法相同 freq={a:1,l:1}
item = 'a'
freq[item]将是1 iffreq[item]将是真实的并且递增freq={a:2,l:1}
添加回答
举报
