今天的題目主要是練習for..in and for..of
,什麼是for..in and for..of
呢?這兩個又有什麼差別呢?
我一開始也不懂,查了網路上好幾篇文章,大概看懂了,也就是說for..in and for..of
是用在遍歷陣列或者物件資料的,而JavaScript有四種迴圈方式:for (let i = 0; i < arr.length; ++i)
arr.forEach((v, i) => { /* ... */ })
for (let i in arr)
for (const v of arr)
上面兩種在前面兩個章節有講解過,這邊就不再贅述,那for..in and for..of
如何分別,如何使用呢?
建議可以參考下面幾篇文章,有助於理解喔!
接下來進入我們今天的題目:
Task
Coding in function giveMeFive, function accept 1 parameter:obj, it's an object.
You need to the traverse the obj, if the length of the object key equals to 5, then push the key value to the array (you need to define the array by yourself, this time I won't help you). Additionally push the value to the array as well, if the length of the value is equal to 5.
Return the five after works finished.
You should use for..in in your code, otherwise, your solution may not pass this kata. Don't learn bad habits from those lazy guys ;-)
也就是說當我物件裡面的key長度為5的話,我就把值回傳到我設定的陣列中,以下是我的解法:
function giveMeFive(obj){
let arr= [];
for(var key in obj){
if(key.length == 5) arr.push(key);
if(obj[key].length == 5) arr.push(obj[key]);
}
return arr
}