What is the difference when we use array names ins

2020-04-14 08:53发布

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] : '';

3条回答
女痞
2楼-- · 2020-04-14 09:04

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.

查看更多
迷人小祖宗
3楼-- · 2020-04-14 09:17

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);

查看更多
老娘就宠你
4楼-- · 2020-04-14 09:19

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

查看更多
登录 后发表回答