简体   繁体   中英

I want to merge array[0] and [1] into an integer array in javascript

I have an array named id_list. It has index 0,1

id_list[0]= 200, 201, 202, 203
id_list[1]= 300, 301, 302, 303

I want to merge index[0] and index[1] into an integer array.
I used .join() but it merges all element including , into the array.

var arr = id_list[0].join(id_list[1]);
console.log(arr[0]);  // result => 2
console.log(arr[1]);  // result => 0
console.log(arr[3]);  // result => ,

I just want as id_list= [200, 201, 202, 203, 300, 301, 302, 303] .
I don't want the , value.

Please help me how to merge them.

Try use Array.prototype.concat

var newArr = id_list[0].concat(id_list[1]);

Fiddle

In your case you can just do:

id_list = id_list[0].concat(id_list[1]);

Read about it here

使用方法concat

id_list[0].concat(id_list[1])

Your example and the way you're getting individual characters in your results suggests that your values are actually strings, like this:

var id_list = [];
id_list[0] = '200, 201, 202, 203';
id_list[1] = '300, 301, 302, 303';

If that's the case, your first step needs to be converting them to actual arrays. You can do that by just splitting on the , but a regular expression that removes the spaces as well will give you a cleaner result. / *, */ will look for a comma with optional spaces before or after it:

id_list[0] = id_list[0].split(/ *, */);
// now id_list[0] is an array of 4 items: ['200', '201', '202', '203']

id_list[1] = id_list[1].split(/ *, */);
// now id_list[1] is an array of 4 items: ['300', '301', '302', '303']

Then you can use concat() to join your arrays into a single array:

var arr = id_list[0].concat(id_list[1]);

I suspect this is more like the output you're expecting:

console.log(arr[0]); // shows 200
console.log(arr[1]); // shows 201
console.log(arr[3]); // shows 203
console.log(arr[5]); // shows 301

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