javascript 将javascript字符串转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52110674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert javascript string to array
提问by user3590094
I have string like this
我有这样的字符串
'10:00','13:00','12:00','15:00','08:00','12:00'
I need it in format like this
我需要这样的格式
Array(3)
数组(3)
Array[0] ['10:00', '13:00']
Array[1] ['12:00', '15:00']
Array[2] ['08:00', '12:00']
I tried with split method but without success.
我尝试使用 split 方法但没有成功。
回答by Nina Scholz
You could replace single quotes with double quotes, add brackes and parse it as JSONand get an array, which is the grouped by two elements.
您可以用双引号替换单引号,添加括号并将其解析为JSON并获得一个数组,该数组由两个元素分组。
var string = "'10:00','13:00','12:00','15:00','08:00','12:00'",
array = JSON
.parse('[' + string.replace(/'/g, '"') + ']')
.reduce((r, s, i) => r.concat([i % 2 ? r.pop().concat(s) : [s]]), []);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
回答by Harunur Rashid
var str = "'10:00','13:00','12:00','15:00','08:00','12:00'";
var oldArray = str.split(',');
var newArray = [];
while(oldArray.length){
let start = 0;
let end = 2;
newArray.push(oldArray.slice(start, end));
oldArray.splice(start, end);
}
console.log(newArray);
回答by Angelos Chalaris
You can use String.split(',')to split into individual values, then group them based on their positions (result of integer division with 2).
您可以使用String.split(',')拆分为单个值,然后根据它们的位置将它们分组(整数除以 2 的结果)。
I am using groupByfrom 30 seconds of code(disclaimer: I am one of the maintainers of the project/website) to group the elements based on the integer division with 2. Short explanation:
我使用GROUPBY从代码30秒(声明:我是项目/网站的维护中的一个)到组基于该整数除法与2.短解释的元素:
Use
Array.map()to map the values of an array to a function or property name. UseArray.reduce()to create an object, where the keys are produced from the mapped results.
用于
Array.map()将数组的值映射到函数或属性名称。使用Array.reduce()创建一个对象,其中,所述密钥是从映射结果产生的。
The result is an object, but can be easily converted into an array using Object.values()as shown below:
结果是一个对象,但可以使用Object.values()如下所示轻松转换为数组:
var data = "'10:00','13:00','12:00','15:00','08:00','12:00'";
const groupBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
acc[val] = (acc[val] || []).concat(arr[i]);
return acc;
}, {});
var arr = data.split(',');
arr = groupBy(arr, (v, i) => Math.floor(i / 2));
arr = Object.values(arr);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
回答by Stefan Blamberg
How about:
怎么样:
"'10:00','13:00','12:00','15:00','08:00','12:00'"
.replace(/'/g, '').replace(/(,[^,]*),/g,";")
.split(';').map(itm => itm.split(','))
回答by Webber
In this case you want to compare 2 values. To do this you can make a for loop that reads the current value and the last value and compares the two. If the last value is higher than current value, the splitting logic happens.
在这种情况下,您要比较 2 个值。为此,您可以创建一个 for 循环来读取当前值和最后一个值并比较两者。如果最后一个值高于当前值,则发生拆分逻辑。
Either you add the current value to the last item (which is an array of strings) in the results array or you add a new array of strings at the end of the results array.
要么将当前值添加到结果数组中的最后一项(它是一个字符串数组),要么在结果数组的末尾添加一个新的字符串数组。
回答by InfiniteStack
One potential solution:
一种可能的解决方案:
let S = "'10:00','13:00','12:00','15:00','08:00','12:00'";
let R = S.split(',');
let I = 0;
let A = new Array([],[],[]);
R.map((object, index) => {
A[I][index % 2] = R[index];
if (index % 2 == 1) I++;
});
console.log(A);
回答by morteza ataiy
I think use JSON.parseis better:
我认为使用JSON.parse更好:
var array = "'10:00','13:00','12:00','15:00','08:00','12:00'";
array = JSON.parse( '[' + array.replace(/'/g,'"') + ']' );
var array2 = [];
for(var i=0;i < array.length - 1; i++){
array2.push([array[i], array[i+1]]);
}
console.log(array2);

