迴圈的用途是重複執行程式碼
for 用法可以控制次數; 而 while 是只要還在有效條件內,都會重複執行
const animals = ["dog", "cat", "sheep", "pig", "cow", "horse"]
let text = ""
for (let i = 0; i < animals.length ; i++){
text += animals[i] + `\n`
}
console.log(text)
處理陣列: arr =[1,2,3] for(let value of arr){ console.log(value)} //1,2,3
也可針對字串做處理:
let keyword = 'health'
let text = ''
for (let x of keyword){
text += x + '<br>'
}
//
h
e
a
l
t
h
for(let key in object){
// code block to be executed
}
const person = {firstName:"Cheryl", lastName:"Li", age: 25};
let text = ""
for ( let x in person){
text += person[x];
}
for..in 迴圈:遞迴物件“person”裡的每一個key/value值
每一個遞迴都會return 一個 key(x)
Key 值通常是拿來存取 key 的 value 值
Key 的 value 值是 person[x]
可搭配使用:
(但是不可配合 continue, break, return 等語句使用,僅能做單純遍歷)
const arr1 = [ 'a', 'b', 'c']
arr1.forEach(element => console.log(element))
//expected output =
"a"
"b"
"c"
forEach 會將陣列裡的所有元素遍歷一遍,如上例子就會把他一個個顯示出來
let x = 1
while (x <= 4){
console.log (`I have looped ${x} time(s)...`)
x++
}
console.log('Finished')