使用reduce方法处理数组元素

Proccessing array elements using reduce method

本文关键字:数组元素 处理 方法 reduce 使用      更新时间:2023-09-26

我有这个数组finalArr = [12,+,4,-,8,*,2];,我想把这个数组减少到一个值,像这样:var result = 12+4-8*2;

下面是我所做的:

var operators = {'+' : function (a,b) {return a + b},
                 '-' : function (a,b){return a - b},
                 '*' : function (a,b){return a * b},
                 '/' : function (a,b){return a / b}};
var opSymbols = ['+','-','*','/'];
finalArr = [12,+,4,-,8,*,2];
finalArr.reduce(function (acc,next,index,arr){
        for (var m = 0; m < opSymbols.length; m++) {
            var op = '';
            if (opSymbols[m] === arr[1]) {
                op = opSymbols[m];
                acc = operators[op](arr[0],arr[2]);
            }
            if (index > 1 && opSymbols[m] === arr[index]) {
                op = opSymbols[m];
                acc +=  arr[index+1];
            }
        }
        return  acc;
    });

我在finalArr中得到语法错误。减少行(SyntaxError:预期表达式,得到','),我认为我没有正确执行减少方法。任何帮助吗?由于

操作符是字符串,因此需要引用它们:

finalArr = [12,'+',4,'-',8,'*',2];

不含reduceeval,但有运算符优先的解

function calculate(a) {
    while (a.length > 1) {
        precedence.some(function (b) {
            return a.some(function (c, i) {
                if (b === c) {
                    return operators[b](a, i);
                }
            });
        });
    }
    return a[0];
}
var operators = {
        '+': function (a, i) {
            a[i - 1] += a.splice(i, 2)[1];
            return true;
        },
        '-': function (a, i) {
            a[i - 1] -= a.splice(i, 2)[1];
            return true;
        },
        '*': function (a, i) {
            a[i - 1] *= a.splice(i, 2)[1];
            return true;
        },
        '(': function (a, i) {
            var j = i + 1, b;
            while (j < a.length) {
                if (a[j] === ')') {
                    b = a.splice(i + 1, j - i);
                    b.pop();
                    a[i] = calculate(b);
                    return true;
                }
                if (a[j] === '(') {
                    return false;
                }
                j++;
            }
        },
        ')': 0
    },
    precedence = ['(', '*', '+', '-'];
console.log(calculate([12, '+', 4, '-', 8, '*', 2]));
console.log(calculate([7, '*', 8, '-', 3.5, '*', 4]));

Eval是邪恶的,
但是如果你想测试它:

finalArr = [12, '+', 4, '-', 8, '*', 2];
console.log(
  eval(finalArr.join(''))
)

如果您的数组是混合字符串/int数组,如

var finalArr = [12,'+',4,'-',8,'*',2];

您可以通过以下命令

生成预期的结果
var result = finalArr.join('');

,如果你需要计算结果

var final = eval(result);

希望对你有帮助;)

如果你真的想使用reduce而不使用eval

var opSymbols = ['+','-','*','/'];
var finalArr = [12,'+',4,'-',8,'*',2];
var result = finalArr.reduce(function (previousValue,currentValue,currentIndex,array){
    var res;
    var opr;
    if(typeof currentValue == 'number') {
            switch(previousValue.operator){
                case '+':
                    res = previousValue.value + currentValue;break;
                case '-':
                    res = previousValue.value - currentValue;break;
                case '*':
                    res = previousValue.value * currentValue; break;
                case '/':
                    res = previousValue.value / currentValue; break;
            }
            opr = previousValue.operator;
    }
    else if(typeof currentValue == 'string') {
        res = previousValue.value;
        opr = currentValue;
    }
    return {'value':res,'operator': opr};

},{'value':0,'operator':'+'});
console.log(result.value); // this gives 16