各种递迴方式:for系列 & while
迴圈的用途是重複执行程式码
for 用法可以控制次数; 而 while 是只要还在有效条件内,都会重複执行
for loop :最基本款的for loop 迴圈
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)
for..of :可使用对象于 Arrays, Strings, Maps, NodeLists 等等
处理阵列: 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>'}//health
for..in :将物件的key-value pair值递迴,可用以下方式ㄧ次取出需求资料
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]
可搭配使用:
取出所有的 key 值 - Object.keys()取出所有的 value - Object.values()取出所有的 pair - Object.entries()forEach Array.forEach() 可遍历出阵列中的每一个元素
(但是不可配合 continue, break, return 等语句使用,仅能做单纯遍历)
const arr1 = [ 'a', 'b', 'c']arr1.forEach(element => console.log(element))//expected output = "a" "b" "c"
forEach 会将阵列里的所有元素遍历一遍,如上例子就会把他一个个显示出来
while
let x = 1while (x <= 4){ console.log (`I have looped ${x} time(s)...`) x++}console.log('Finished')