简体   繁体   English

如何使用JavaScript从输入字符串创建数组?

[英]How can I create an array from an input string using JavaScript?

Currently I have a PHP page returning some values. 目前,我有一个PHP页面返回一些值。 The data is something like this: 数据是这样的:

08-30-2018, in
08-29-2018, out
08-28-2018, in
08-27-2018, in

How can I create a custom array in Javascript with the values above to be similar as this array below: 如何使用上面的值在Javascript中创建自定义数组,使其与下面的数组类似:

var system = [
   ['08-30-2018', 'in'],
   ['08-29-2018', 'out'],
   ['08-28-2018', 'in'],
   ['08-27-2018', 'in']
];

I have tried array.push , but it does not create an array like above. 我已经尝试了array.push ,但是它没有创建像上面这样的数组。 What should I do? 我该怎么办? Can you help me? 你能帮助我吗? Thank you! 谢谢!

You can use multi-dimensional arrays in JavaScript 您可以在JavaScript中使用多维数组

 var system = []; var output = "08-30-2018, in\\n08-29-2018, out\\n08-28-2018, in\\n08-27-2018, in"; var items = output.split("\\n"); for(i=0; i<items.length; i++){ var data = items[i].split(","); var item = []; item.push(data[0].trim()); item.push(data[1].trim()); system.push(item); } console.log(system); 

You could also parse this kind of input using regular expressions: 您还可以使用正则表达式解析此类输入:

const input = '08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in';
const regex = /(\d{2}-\d{2}-\d{4}), (in|out)/g;

let system = [];
let match;
while ((match = regex.exec(input)) !== null) {
    system.push([match[1], match[2]]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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