今天的題目主要是練習break,continue
的用法,這兩個有什麼不一樣呢?又該如何使用呢?
break:強制退出循環,從這個迴圈中完全退出,不再繼續執行。
continue:停止當前迭代,執行下一次迭代,簡單來說,當遇到某條件時,自動跳過,再繼續後面的迴圈。
下面是今天的題目:
Task
Coding in function grabDoll. function accept 1 parameter:dolls. it's a string array, a list of some dolls.
You need traverse dolls by using for loop. If element is "Hello Kitty" or "Barbie doll", you should push it to a bag(bag is an array, I've defined in the function); if it's other strings, we should use continue skip it.
When the bag has three element, bag is full. You should use break jump out the loop; If bag is not full, you should traverse dolls until the last element.
Return the bag after for loop finished.
簡單來說,今天的任務是,這個for迴圈中如果有"Hello Kitty"或"Barbie doll"兩個字串,就回傳到bag的陣列中,且如果bag已有三個element,這個迴圈就停止,下面是我的解法:
function grabDoll(dolls){
var bag=[];
for(let i = 0; i<dolls.length; i++){
if(dolls[i] == "Hello Kitty" || dolls[i] == "Barbie doll"){
bag.push(dolls[i])
}else{
continue;
}
if(bag.length >=3){
break;
}
}
return bag;
}
設for迴圈i從0開始,i小於dolls陣列的長度,i遞增,
設一個if判斷,dolls[i] == "Hello Kitty" || dolls[i] == "Barbie doll"
如果dolls陣列有"Hello Kitty"或"Barbie doll",我就push到bag陣列中,
else設定continue,表示我繼續跑後面的程式,不做其他事情(我當忽略用XD)
再設定一個if判斷,如果bag.length
大於三,我就停止這個迴圈。
這樣就完成了!