如何在Javascript中为每个索引拆分一些数组到几个数组

时间:2015-10-03 14:15:40

标签: javascript arrays split

我试图用空格分割字符串。

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

它会输出如下:

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

我需要结果如下:

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

如何拆分该数组或从第一个结果开始。

感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

如果你的示例输出是一个错误并且你真的想要一个数组数组,其中每个从属数组都是三个条目长,你可以通过使用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>

或者,如果您想通过检测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>

...但是你说你想通过索引来做,所以......

答案 1 :(得分:0)

您可以尝试通过非空白/空白元组进行匹配,然后添加量词:

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

这会在第3个元素的末尾留下空格,因此可能需要修剪

答案 2 :(得分:0)

这可以使用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));

您正在寻找解析JavaScript吗?

如果您正在寻找解析JavaScript,您应该查看at Esprima并使用抽象语法树以编程方式分析表达式。

例如,如果您将字符串拆分为"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"
}

这听起来很复杂,但是一旦你进入它,解析会让事情变得更容易! 你可以玩Esprima using its online parser demo

答案 3 :(得分:0)

您可以尝试匹配项目后跟=!&lt; 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;