What is the difference when we use array names instead of spread operator?

江枫思渺然 提交于 2019-12-20 03:23:13

问题


What is the difference if I use:

var numbers = [1, 2, 3]
var mainArray = (numbers.length > 1) ? numbers : '';

instead of this:

var numbers = [1, 2, 3]
var mainArray = (numbers.length > 1) ? [...numbers] : '';

回答1:


Since assigment of data structures points to the same space in memory, if you have two variables referencing the same array, altering one variable will alter the other. That is to say:

if x = [1, 2, 3] and y = x then we say x.push(5) y will also have that 5 because they are pointing to the same instance. If you use [...x] you are creating a copy of x. It consumes O(n) memory, a new reference. So if x is altered, y will be uneffected.

spreads are clean and neat but they do have overhead. They will effect performance if used on a very large data set.




回答2:


The difference if you use:

var numbers = [1, 2, 3]
var mainArray = (numbers.length > 1) ? numbers : '';
//mainArray == numbers => true

Here it will assign reference of numbers to mainArray

instead of this:

var numbers = [1, 2, 3]
var mainArray = (numbers.length > 1) ? [...numbers] : '';
//mainArray == numbers => false

Here it will create new array from numbers's elements and will assign it to mainArray




回答3:


The spread operator (...) spreads out an array into individual values instead of an array of values. As is shown in the below code snippet numbers is an array of integers while ...numbers is 3 separate integers. So [...numbers] will give you a new array with the same values and numbers is just a reference to the existing array.

var numbers = [1, 2, 3]
console.log(numbers);
console.log(...numbers);


来源:https://stackoverflow.com/questions/50707456/what-is-the-difference-when-we-use-array-names-instead-of-spread-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!