实例演示分支与循环结构
单分支
双分支
let status = true
if (status) {
console.log('Success')
}
多分支
status = false
if (status) {
console.log('Success')
} else {
console.log('Fail')
}
循环结构
let age = 7
if (age >= 18 && age < 60) {
console.log('请放心观看')
} else if (age >= 60) {
console.log('请在子女的陪同下观看')
} else {
console.log('未成年,禁止观看')
}
- 三要素:
— 初始化: 从哪里开始,入口
— 条件: 到哪里结束,true继续,false停止
— 更新条件: 避免死循环
while
let arr = ['red', 'green', 'blue']
console.log(arr)
let i = 0
console.log(arr.length)
while (i < arr.length) {
console.log(arr[i])
i++
}
for,while的简化
for (let i = 0; i < arr.length;i++) {
console.log(arr[i])
}
for-of: 遍历”数组”,只关注值
for (let value of arr) {
console.log(value)
}
for-in: 遍历”对象”
const user = { id:5, myname:'jay', salary:6000 }
for (let key in user){
console.log(user[key])
}
forEach: 遍历”数组”
arr.forEach(function (item) {
console.log(item)
})
map: 遍历数组,与 forEach 使用方法一样,只不过有一个返回值
arr = [1, 2, 3]
let res = arr.map(item => item * 2)
console.log(res)