简体   繁体   中英

Javascript Array concat function

case1

let history = [{temp : 123}];
history.concat({temp:1234}); //[{temp :123}, {temp:1234}]

case2

let history = [{temp : 123}];
history.concat([{temp:1234}]): //[{temp :123}, {temp:1234}]

case3

let history = [{temp : 123}];
history.concat([[{temp:1234}]]); //[{temp :123}, [{temp:1234}]]

why concat method returns same output in case1 and case2?

According to me case1 and case3 is expected, but case2 is unexpected.

case1: array.concat(nonArray) -> add the nonArray to the array

case2: array.concat(newArray) -> add every element of newArray to the array

case3: array.concat(twoDArray) -> add every element of twoDArray to the array, but every element of the twoDArray IS ITSELF an array.

case2 actually behaves exactly the same as case3

The concat method creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array). It does not recurse into nested array arguments.

const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];

letters.concat(numbers);
// result in ['a', 'b', 'c', 1, 2, 3]
const letters = ['a', 'b', 'c'];

const alphaNumeric = letters.concat(1, [2, 3]);

console.log(alphaNumeric); 
// results in ['a', 'b', 'c', 1, 2, 3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM