···js
// 1.数组
const arr = [1, “uname”, “12355”]
console.log(arr)
console.table(arr)
console.log(arr[0], arr[1], arr[2])
console.log(typeof arr)
console.log(Array.isArray(arr))
console.log(“=====================”)
// 2.对象
let user = {
id: 1,
uname: “武大”,
pwd: “12345”,
“his wife”: “金莲”,
show: () => id=${this.id},uname=${this.uname}
,
say: function () {
return id=${this.id},uname=${this.uname},pwd=${this.pwd},his wife=${this["his wife"]}
},
// 箭头函数没有自己的this,默认和上下文绑定,父级作用域
}
console.log(user.id, user.uname, user.pwd, user[“his wife”])
console.log(user.show())
console.log(user.say())
执行结果如下:
![](https://img.php.cn/upload/image/717/121/644/1676721460121472.png)
## 2. 演示作用域与作用链
···js
// 作用域
{
let uname = "老大"
console.log(uname)
}
// console.log(uname)
// 代码块外访问不到
console.log("=================")
// 函数作用域及作用域链
let www = "www.baidu.com"
const tell = function () {
// let www = "百度网"
console.log(www)
}
tell()
// 块或函数内部访问变量,顺序由内到外。内部没有,才找外部全局变量
运行结果:
// 对象的简化方法
let shop = {
name: "水蜜桃",
price: 20,
weight: 10,
total: function () {
return `
商 品:${this.name}
单 价:${this.price}元/斤
重 量:${this.weight}斤
应付金额:${this.price * this.weight}元`
},
}
console.log(shop.total())
console.log("===========================")
shop = {
name: "土鸡蛋",
price: 20,
weight: 5,
total() {
return `
商 品:${this.name}
单 价:${this.price}元/斤
重 量:${this.weight}斤
应付金额:${this.price * this.weight}元`
},
}
// 简化方法:删除’:function‘,不是箭头函数
console.log(shop.total())
console.log("===========================")
shop = {
name: "芒果",
price: 40,
weight: 10,
total: () => `
商 品:${shop.name}
单 价:${shop.price}元/斤
重 量:${shop.weight}斤
应付金额:${shop.price * shop.weight}元`,
}
//一定要用箭头函数的话,不能用this,应直接采用对象名称。 比较麻烦
console.log(shop.total())
``
运行结果:
![](https://img.php.cn/upload/image/719/430/385/1676723372428458.png)
## 4. 演示分支结构与对应的语法糖
```js
// 1.单分支
let person = null
if (!person) {
console.log("nobody!")
}
console.log("------------------")
// 2.双分支
person = 5
if (!person) {
console.log("nobody!")
} else {
console.log("开张了!")
}
console.log("------------------")
// 语法糖
person = 0
console.log(person ? "开张了!" : "nobody!")
console.log("------------------")
// 3.多分支
person = 10000
if (person < 100) {
console.log("生意冷清!")
} else if (person < 5000) {
console.log("生意兴隆!")
} else {
console.log("快升级服务器!")
}
console.log("------------------")
// 语法糖
person = 2000
switch (true) {
case person < 1000:
console.log("生意冷清!")
break
case person >= 1000 && person < 5000:
console.log("生意兴隆!")
break
case person >= 5000:
console.log("快升级服务器!")
break
default:
break
}
运行结果:
000