3 回答

TA貢獻1995條經(jīng)驗 獲得超2個贊
首先,請記住,在使用 迭代字符串時for..of
,為每個循環(huán)聲明的項目(您已命名為item
)是字符串的每個字符。
由于該對象一開始是空的,freq[item]
因此最初是undefined
. 例如,在第一次迭代中,{}['a']
isundefined
是假的,因此else
輸入:
freq['a'] = 1;
a
在隨后的迭代中,當(dāng)找到該字符時,該a
屬性將存在于對象上,因此if
輸入 ,增加該屬性值:
freq['a']++;

TA貢獻1898條經(jīng)驗 獲得超8個贊
第一次發(fā)現(xiàn)不在對象中的字母時,它將返回 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條經(jīng)驗 獲得超3個贊
在 javascript 中以下是錯誤的 "",false,0,undefined,null
..在你的情況下 freq 是一個空對象
freq ={}
在循環(huán)的第一次迭代中
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}
添加回答
舉報