使用数字和运算符转换数组

时间:2018-04-06 11:50:23

标签: javascript arrays

我设法有这个arraylist:

["1","2","+","2","1","2"]

但是我想对它进行排序以便

["12","+","212"]

但我无法弄清楚如何做到这一点。

更新:

let al = ["1","2","+","2","1","2"];
for(let i=0;i.length;i++) {
  if(al[i] != "+" && al[i+1]) {
    al[i] += al[i+1];
   }
}

我想我可以使用while循环

4 个答案:

答案 0 :(得分:3)

通过正则表达式组合连接和拆分:

    
    var a = ["1","2","+","2","1","2"];
    a = a.join('').split(/([x^+-])/);

    console.log(a);

答案 1 :(得分:2)

你可以通过单词边界位置加入和拆分,而不提操作符。



var array = ["1", "2", "+", "2", "1", "2"],
    result = array.join('').split(/\b/);

console.log(result);




答案 2 :(得分:0)

只需遍历数组并加入除+之外的所有内容:

const array = ["1", "2", "+", "2", "1", "2"]
const result = [];
let curr = "";

for (const el of array) {
  if (el == "+") {
    result.push(curr, el);
    curr = "";
  } else {
    curr += el;
  }
}

result.push(curr);
console.log(result)

答案 3 :(得分:0)

这是最简单的方法。只需编写一个reducer来将令牌附加到堆栈。



const OPERATORS = /[+\-\*\/]/;
function toExpression(tokens) {
  return tokens.reduce((result, token) => {
    if (OPERATORS.test(token)) {
      result.push(token, '');
    } else {
      result[result.length - 1] += token;
    }
    return result;
  }, ['']);
}

let arr1 = ["1", "2", "+", "2", "1", "2"];
let arr2 = toExpression(arr1);

console.log(JSON.stringify(arr2));

.as-console-wrapper { top: 0; max-height: 100% !important; }