03.ES6数组对象展开(spread)

2020-06-02  本文已影响0人  __豆约翰__

数组对象展开

// Create an Array
const tools = ['hammer', 'screwdriver']
const otherTools = ['wrench', 'saw']
// Unpack the tools Array into the allTools Array
const allTools = [...tools, ...otherTools]

console.log(allTools)

output:

["hammer", "screwdriver", "wrench", "saw"]
// Array of users
const users = [
  { id: 1, name: 'Ben' },
  { id: 2, name: 'Leslie' },
]
// A new user to be added
const newUser = { id: 3, name: 'Ron' }
const updatedUsers = [...users, newUser]

console.log(users)
console.log(updatedUsers)

output

[{id: 1, name: "Ben"}
 {id: 2, name: "Leslie"}]

[{id: 1, name: "Ben"}
 {id: 2, name: "Leslie"}
 {id: 3, name: "Ron"}]

浅拷贝

// Create an Array
const originalArray = ['one', 'two', 'three']

// Use spread to make a shallow copy
const secondArray = [...originalArray]

// Remove the last item of the second Array
secondArray.pop()

console.log(originalArray)

output

["one", "two", "three"]

转换可迭代对象为数组

// Create a set
const set = new Set()

set.add('octopus')
set.add('starfish')
set.add('whale')
// Convert Set to Array
const seaCreatures = [...set]

console.log(seaCreatures)

output

["octopus", "starfish", "whale"]
const string = 'hello'

const stringArray = [...string]

console.log(stringArray)

output

["h", "e", "l", "l", "o"]

对象展开

// Create an Object and a copied Object with Object.assign()
const originalObject = { enabled: true, darkMode: false }
const secondObject = Object.assign({}, originalObject)
console.log(secondObject)

等价于

// Create an object and a copied object with spread
const originalObject = { enabled: true, darkMode: false }
const secondObject = { ...originalObject }

console.log(secondObject)

output

{enabled: true, darkMode: false}
const user = {
  id: 3,
  name: 'Ron',
}

const updatedUser = { ...user, isLoggedIn: true }

console.log(updatedUser)

output

{id: 3, name: "Ron", isLoggedIn: true}
const user = {
  id: 3,
  name: 'Ron',
  organization: {
    name: 'Parks & Recreation',
    city: 'Pawnee',
  },
}
const updatedUser = { ...user, organization: { position: 'Director' } }

console.log(updatedUser)

output

id: 3
name: "Ron"
organization: {position: "Director"}

organization被覆盖
正确的做法

const updatedUser = {
  ...user,
  organization: {
    ...user.organization,
    position: 'Director',
  },
}

console.log(updatedUser)

output

id: 3
name: "Ron"
organization: {name: "Parks & Recreation", city: "Pawnee", position: "Director"}
上一篇下一篇

猜你喜欢

热点阅读