简体   繁体   English

如何在Javascript中为每个索引将数组拆分为多个数组

[英]How to split some array to several array for every some index in Javascript

I'm trying to split a string by whitespace. 我正在尝试按空格分割字符串。

var conditionSplit = "item == 2 item !== 1 item <= 5".match(/\S+/g);

It will give output like: 它将给出如下输出:

// ["item", "==", "2", "item", "!==", "1", "item", "<=", "5"];

I need the result to be like: 我需要的结果是这样的:

// [["item","==","2"],["item","!==","1"],["item","<=","5"]]

What should I do to split that array or going from the first result. 我应该怎么做才能拆分该数组或从第一个结果开始。

Thanks for help. 感谢帮助。

If your sample output is an error and you really want an array of arrays, where each of the subordinate arrays is three entries long, you can do that by using forEach and pushing a new array onto a result array whenever the index you're visiting is evenly divisible by 3: 如果您的示例输出是一个错误,并且您确实想要一个数组数组,其中每个从属数组的长度为三个条目,则可以通过使用forEach并将每当要访问index时候将一个新数组推入结果数组来做到这一点被3整除:

 var conditionSplit = "item == 2 item !== 1 item <= 5".match(/\\S+/g); var result = []; var current; conditionSplit.forEach(function(entry, index) { if (index % 3 == 0) { current = []; result.push(current); } current.push(entry); }); snippet.log(JSON.stringify(result)); 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

Or if you wanted to do it by detecting the item string, you just change if (index % 3 == 0) to if (entry == "item") : 或者,如果您想通过检测item字符串来做到这一点,只需将if (index % 3 == 0)更改为if (entry == "item")

 var conditionSplit = "item == 2 item !== 1 item <= 5".match(/\\S+/g); var result = []; var current; conditionSplit.forEach(function(entry) { if (entry == "item") { current = []; result.push(current); } current.push(entry); }); snippet.log(JSON.stringify(result)); 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

...but you said you wanted to do it by index, so... ...但是您说您想按索引进行操作,所以...

You could try to match by non-whitespace/whitespace tuples and then add a quantifier: 您可以尝试按非空白/空白元组进行匹配,然后添加一个量词:

([^\S]+\S*){3}

This will leave you with whitespace at the end of the 3rd element though, so trimming may be required 不过,这将使您在第三个元素的末尾留有空格,因此可能需要修剪

This can be solved using Array.prototype.reduce : 这可以使用Array.prototype.reduce解决:

 // This variable will contain the "array of arrays", where each // index will be an array of each expression as you requested... var allResults = []; "item == 2 item !== 1 item <= 5" .match(/\\S+/g) .reduce(function(result, next) { // Whenever an "item" string is detected, this starts // a new array item if (next == "item") { result = []; allResults.push(result); } result.push(next); return result; }, null); alert(JSON.stringify(allResults)); 

Are you looking for parsing JavaScript? 您是否要解析JavaScript?

If you're looking for parsing JavaScript, you should take a look at Esprima and use an abstract syntax tree to analyze expressions programmatically. 如果要解析JavaScript,则应查看Esprima并使用抽象语法树以编程方式分析表达式。

For example, if you split your string by "item" , and you parse every expression, you would get something like the following AST: 例如,如果用"item"分割字符串,然后解析每个表达式,则会得到类似以下AST的内容:

// item == 2 would be:

{
    "type": "Program",
    "body": [
        {
            "type": "ExpressionStatement",
            "expression": {
                "type": "BinaryExpression",
                "operator": "==",
                "left": {
                    "type": "Identifier",
                    "name": "item"
                },
                "right": {
                    "type": "Literal",
                    "value": 2,
                    "raw": "2"
                }
            }
        }
    ],
    "sourceType": "script"
}

It sounds complicated, but parsing makes things easier once you get into it! 听起来很复杂,但是一旦解析,解析起来将变得更加容易! You can play with Esprima using its online parser demo . 您可以使用Esprima 的在线解析器演示来玩。

You could try to match item followed by =!<0-9 and split each element. 您可以尝试匹配后跟=!<0-9的项目并拆分每个元素。

 var sa = "item == 2 item !== 1 item <= 5".match(/item[ =!<0-9]+/g);
        var n = sa.length;
        var ar = new Array(n);
        for (i = 0; i < n; i++) ar[i] = sa[i].split(" ");
        document.getElementById('fg').innerHTML = ar;

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

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