数组、对象、作用域与作用链、对象的简化方案、分支结构与对应的语法糖

数组、对象、作用域与作用链、对象的简化方案、分支结构与对应的语法糖

1. 数组、对象、作用域与作用链、对象的简化方案、分支结构与对应的语法糖

1. 演示数组与对象的声明与访问

···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 源码网点我wcqh.cnuser = {

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”])

c源码网点我wcqh.cnonsole.log(user.show())

console.log(user.say()) 执行结果如下:![](https://img.wcqh.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()源码网点我wcqh.cn{// let www = “百度网” console.log(www)}tell()// 块或函数内部访问变量,顺序由内到外。内部没有,才找外部全局变量

运行结果:

3. 代码描述对象的简化方案

// 对象的简化方法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(“======源码网点我wcqh.cn=====================”)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:()=>源码网点我wcqh.cn`品:${shop.name}价:${shop.price}元/斤量:${shop.weight}斤应付金额:${shop.price * shop.weight}元`,}//一定要用箭头函数的话,不能用this,应直接采用对象名称。 比较麻烦console.log(shop.total())运行结果:![](https://img.wcqh.cn/upload/image/719/430/385/1676723372428458.png)##4.演示分支结构与对应的语法糖“`js// 1.单分支let person =nullif(!person){ console.log(“nobody源码网点我wcqh.cn!”)}console.log(“——————“)// 2.双分支person =5if(!person){ console.log(“nobody!”)}else{ console.log(“开张了!”)}console.log(“——————“)// 语法糖person =0console.log(person ?“开张了!”:“nobody!”)console.log(“——————“)// 3.多分支person =10000if(person <100){ console.log(“生意冷清!”)}elseif(person <5源码网点我wcqh.cn000){ console.log(“生意兴隆!”)}else{ console.log(“快升级服务器!”)}console.log(“——————“)// 语法糖person =2000switch(true){case person <1000: console.log(“生意冷清!”)breakcase person >=1000&& person <5000: console.log(“生意兴隆!”)breakcase person >=5000: console.log(“快升级服务器!”)breakdefault:break}

运行结果:

000
批改老师:PHPz 批改状态:合格 老师批语:源码网点我wcqh.cn
作者最新博文
2023-02-10 12:29:00

© 版权声明
THE END
喜欢就支持一下吧
点赞809 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容