这是一个非常简单的计算器的例子,用于学习Array.reduce / map。
如何将startValue
数组与混合运算符类型(仅+/-)相加?
我有一系列我希望映射的输入,然后缩小以获得总和。
const sum = (p,c) => {
return p + c;
};
let startValue = [1,2,3,'+',3,'+',4,'-',5,'+','-',5,3];
const finalValue = startValue
.map(combineNumbersWithOperators) //or reduce
.reduce(sum)
第一个减速器将输出:
startValue.map(combineNumbersWithOperators)
// [123,3,4,-5,-53]
第二个减速器应按预期工作:
[123,3,4,-5,-53].reduce(sum)
// = 123
答案 0 :(得分:0)
看起来您的第一个示例与您的预期签名约定不一致。根据数组第一部分5,3
的组合方式,数组中的最后一个1,2,3
应解析为53。此外,我忽略了数组中孤立的-
符号,因为它不清楚/无法解释。
此解决方案仅使用.reduce();我不认为地图或过滤器是必要的。
var flat = startValue.reduce(function(a,b) {
if (b.toString() === '-') {
var arr = a.toString().split('%');
arr[arr.length - 1] = '-' + arr[arr.length-1];
return arr.join('%') + '%';
} else if (b.toString() === '+') {
return a.toString() + '%';
}
return a.toString() + b.toString();
}).split('%').reduce(function(a,b){
if (b === '-') {
return a;
}
return a + parseInt(b);
},0)
答案 1 :(得分:0)
我会使用forEach
和一些实用功能一次性完成。
从头到尾:
const array = [1,2,3,'+',3,'+',4,'-',5,'+','-',5,3];
let result = 0; /* the final result */
let numberAggregator = ''; /* used to aggregate the numbers */
let operator = '+'; /* last operator found, start by adding the first number */
const parseAggregator = function(aggregator) {
let number = parseFloat(aggregator);
if (isNaN(number)) {
number = 0;
}
return number;
};
const performOperation = (left, right, operator) => {
/* perform the lat operator's function */
switch (operator) {
case '+':
return left + right;
case '-':
return left - right;
default:
/* you could add other operators here */
return left; /* silently fail for unsupported operators :( */
}
};
array.forEach(input => {
if (isNaN(parseInt(input, 10)) && input !== '.') { /* it's an operator */
/* parse the last aggregated number */
const lastNumber = parseAggregator(numberAggregator);
numberAggregator = '';
/* perform the operation */
result = performOperation(result, lastNumber, operator);
/* save the new operator */
operator = input;
} else {
/* add the input to the number aggregator */
numberAggregator += input;
}
});
/* once you get to the end, perform the last operation cached */
const lastNumber = parseFloat(numberAggregator);
result = performOperation(result, parseAggregator(numberAggregator), operator);
console.log(result); /* 123 + 3 + 4 - 5 - 53 = 72 */
答案 2 :(得分:-1)
map
会将映射数组的每个值转换为其他值。这意味着在通过map
运行数组之后,数组的长度(即元素数量)仍然相同。要实现您的要求,可以使用filter
(请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)。
所以你的例子会变成:
startValue.filter(combineNumbersWithOperators)
// [123,3,4,-5,-5,3]```