console.log("1. while循环:")
const arr = ["唐僧", "孙悟空", "猪八戒", "沙悟净"]
let i = 0
while (i < arr.length) {
console.log(arr[i])
i++
}
console.log("----------------------")
console.log("2. for循环:")
for (i = 0; i < arr.length; i++) {
console.log(arr[i])
}
console.log("----------------------")
console.log("3. for-of 遍历数组")
for (let val of arr) {
console.log(val)
}
console.log("----------------------")
console.log("4. for-in 遍历对象")
let westtral = {
teacher: "唐僧",
fbro: "孙悟空",
sbro: "猪八戒",
tbro: "沙悟净",
}
for (let key in westtral) {
console.log(`${key}=>${westtral[key]}`)
}
// 注意:不能用obj.key,避免出线非法字符
console.log("----------------------")
console.log("5.forEach/map: 遍历“数组“")
arr.forEach(function (item, index, arr) {
console.log(item, index, arr)
})
arr.forEach(function (item) {
console.log(item)
})
console.log(".....................")
console.log("箭头函数:")
arr.forEach(item => console.log(item))
console.log(".....................")
console.log("测试forEach方法有无返回值")
let res = arr.forEach(item => item)
console.log(res)
console.log(".....................")
console.log("测试map方法有无返回值")
res = arr.map(item => item)
console.log(res)
console.log(".....................")
console.log("map方法小应用:")
res = arr
.map(
item => `<li>${item}</li>
`
)
.join("")
res = "<ul>\n" + res + "</ul>"
console.log(res)
运行结果如下:
···js
// 数组结构和赋值
const score = [100, 90, 90]
let [a, b, c] = score
console.log(a, b, c)
let [company, site] = [“百度”, “www.baidu.com”]
console.log(company, site)
;[company, site] = [“阿里”, “www.alibaba.com”]
console.log(company, site)
;[company, site, ceo = “不详”] = [“阿里”, “www.alibaba.com”]
console.log(company, site, ceo)
;[company, site, …arr] = [“阿里”, “www.alibaba.com”, “Jack Ma”, 50]
let [boss, age] = arr
console.log(company, site, boss, age)
console.log(“—————————————————————“)
// 对象
// 默认变量名和属性相同
//I 变量与当前作用域中的变量命名冲突时,用别名访问
let { id, fruits: fname } = { id: 1, fruits: “水蜜桃” }
console.log(id, fname)
// 复制对象
let prj = { id: 1, pname: “合肥明悦广场” }
console.log(prj)
let { …obj } = prj
console.log(prj === obj)
// 结构传参
let show = function (prj) {
return id:${prj.id} pname:${prj.pname}
}
prj = { id: 2, pname: “上海中心大厦” }
console.log(show(prj))
```
运行结果如下: