简体   繁体   中英

Proper way to add an object to an array using concat

var obj = {name: 'tim', bio: 'lol'};

var arr = [{name: 'beba', bio:'lulu'}, {name: 'keh', bio: 'kih'}];

var newArr = arr.concat([obj]);
or
var newArr = arr.concat(obj);

Both concats work but one is with square brackets and the other without them. Are they both correct?

If you look at the docs of concat

Yes it is fine. concat function is flexible enough.

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.

It internally checks what you are passing and do the things.

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

Update :

var newArr = arr.concat(obj);

Means you are passing a single object to concat function.

var newArr = arr.concat([obj]);

Means you are passing an array with being a single object in it.

Basically [] denotes an array.

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