Destructuring Assignment in JS(解构assignment in js)

Destructuring Assignment In JavaScript

 

更省事,代码显得也清楚。

Arrays

传统的声明赋值:

let johnDoe = ["John", "Doe", "Iskolo"]
let firstName = johnDoe[0]
let lastName = johnDoe[1]
let title = johnDoe[2]

 

现代声明和赋值使用:拆解JS中的分配(赋值)

let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName, title] = johnDoe
console.log(firstName, lastName, title) // John Doe Iskolo

 

 

 

 循环:

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
}
Object.keys(obj).forEach(key => {
  console.log(`${key} : ${obj[key]}`)
})

 

解释

Object.keys()得到obj的key的数组集合。 

Array.protptype.forEach()

 

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
}
for(let [key, value] of Object.entries(obj)) {
  console.log(`${key} : ${value}`)
}

 

使用for...of循环一个String, Array, Array-like objects的数据。

Object.entries()得到:

(3) [Array(2), Array(2), Array(2)]
0: (2) ["firstName", "John"]
1: (2) ["lastName", "Doe"]
2: (2) ["title", "Iskolo"]
length: 3
__proto__: Array(0)

 

注意:for...in ,循环的是一个对象的properties。


 

 

分配默认值

let [firstName="John", , title="Fire"] = "John Doe".split(" ") //undefined firstName //"John" title //"Fire"

 

"John Doe".split(" ") 会得到["John", "Doe"]

firstName被赋值"John"

nil被赋值"Doe", 所以不存在。

title没有被赋值,所以使用默认的"Fire"

 


 

 

Objects

使用

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
}

let {firstName, lastName) = obj
console.log(firstName, lastName) // John Doe

 

 

使用Object来传递Function arguments

function sumFunc(a = true, b = "", c = "", d = 0, e = false) {
  console.log(a,b,c,d,e)
}
// Call the function
sumFunc(true, "", "", "", true)
// Or if we want to preserve default values
sumFunc(true, undefined, undefined, undefined, true)

 

一个函数定义了5个参数,那么使用这个函数时,也要添加上5个参数,否则会报告❌。

如果是更多的参数,就太费劲了。

把参数变为一个对象。使用这个函数时,把要传入的参数也用对象的形式,就非常方便了

function sumFunc({a = true, b = "", c = "", d = 0, e = false}) {
  console.log(a,b,c,d,e)
}
let args = {a : false, e: true}
// Call the function
sumFunc(args)

 

转载于:https://www.cnblogs.com/chentianwei/p/10153866.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值