javascript 解构分配

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 解构分配相关的知识,希望对你有一定的参考价值。

// consider the below object, it has 4 keys but we only want to use the values of two
// we can scope bread and meat to be used locally
var sandwich = {
  bread: "dutch crunch",
  meat: "tuna",
  cheese: "swiss",
  toppings: ["lettuce", "tomato", "mustard"]
}

// the code below pulls bread and meat out of the object and creates local variables for them.
var {bread, meat} = sandwich
console.log(bread, meat)  // dutch crunch tuna

// the bread and meat variables can also be changed
bread = "garlic"
meat = "turkey"
console.log(bread)  // garlic
console.log(meat)   // turkey

// object properties remain unchanged due to scope of bread and meat variables
console.log(sandwich.bread, sandwich.meat)  // dutch crunch tuna




// we can also DESTRUCTURE INCOMING FUNCTION ARGUMENTS.
// consider this function that would log a person's name as a lord
var lordify = regularPerson => {
 console.log(`${regularPerson.firstName} of Canterbury`)
}

var regularPerson = {
  firstName: "Bill",
  lastName: "Wilson"
}

lordify(regularPerson)    // Bill of Canterbury

// instead of using dot notation, we can destructure the values we need, as follows
var lordify = ({firstName}) => {
  console.log(`${firstName} of Canterbury`)
}

lordify(regularPerson)    // Bill of Canterbury



//DESTRUCTURING VALUES FROM ARRAYS
var [firstResort] = ["Kirkwood", "Squaw", "Alpine"]
console.log(firstResort)    // Kirkwood

// we can pass over values by using commas
var [,,thirdResort] = ["Kirkwood", "Squaw", "Alpine"]
console.log(thirdResort)    // Alpine

以上是关于javascript 解构分配的主要内容,如果未能解决你的问题,请参考以下文章

Javascript通过解构重新分配let变量[重复]

javascript 解构分配

javascript 使用解构分配从数组中分配变量

javascript 使用解构分配将对象作为函数的参数传递

必须在构造函数中使用解构道具分配错误[重复]

如何在 JavaScript 中让代码更加精简