Skip to content

Instantly share code, notes, and snippets.

@cwy007
Created November 16, 2018 23:55
Show Gist options
  • Save cwy007/6b396d44e957aba9f9d3ee57b3ab7563 to your computer and use it in GitHub Desktop.
Save cwy007/6b396d44e957aba9f9d3ee57b3ab7563 to your computer and use it in GitHub Desktop.
Array(amount).fill(object)

源代码

this.addProduct = function(amount, product) {
  products.push(...Array(amount).fill(product));
};

解释

Array(amount).fill(object)

Array(3)                    // => [null, null, null]
Array(3).fill({ a: 1})      // => [{ a: 1 }, { a: 1 }, { a: 1 }]

command line

> amount = 3
3
> product = { name: 'p  name', price: 10}
{ name: 'p  name', price: 10 }
> a = Array(amount)
[ <3 empty items> ]
> amount
3
> a.fill(product)
[ { name: 'p  name', price: 10 },
  { name: 'p  name', price: 10 },
  { name: 'p  name', price: 10 } ]
> a
[ { name: 'p  name', price: 10 },
  { name: 'p  name', price: 10 },
  { name: 'p  name', price: 10 } ]

原文链接

https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a?fbclid=IwAR0KTJOgQOSpqTT6Nw2I_-IxPeJw3o-SIbnDCb9HhBAgGkNp9OIEfoydTmo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment