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)

 

posted @ 2018-12-21 09:37  Mr-chen  阅读(186)  评论(0编辑  收藏  举报