[英]I want to merge array[0] and [1] into an integer array in javascript
I have an array named id_list. 我有一个名为id_list的数组。 It has index 0,1
它有索引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. 我想将
index[0]
和index[1]
合并为一个整数数组。
I used .join()
but it merges all element including ,
into the array. 我用
.join()
但它合并所有元件,包括,
到阵列。
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]
. 我只想要
id_list= [200, 201, 202, 203, 300, 301, 302, 303]
。
I don't want the ,
value. 我不想要
,
价值。
Please help me how to merge them. 请帮我如何合并它们。
使用方法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: 然后你可以使用
concat()
将你的数组连接成一个数组:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.