Javascript 使用reduce对节点中的js文件参数求和
在节点中运行js文件时,我试图获取参数(fom second arg),然后求和它们Javascript 使用reduce对节点中的js文件参数求和,javascript,arrays,node.js,reduce,Javascript,Arrays,Node.js,Reduce,在节点中运行js文件时,我试图获取参数(fom second arg),然后求和它们 var args = 0; process.argv.reduce((a, b, c) => { if (c > 1) { console.log(+a + +b); this.args += +a + +b; } return a }, 0); console.log(args) 结果,当我运行nodeexlearnyonode.js 1
var args = 0;
process.argv.reduce((a, b, c) => {
if (c > 1) {
console.log(+a + +b);
this.args += +a + +b;
}
return a
}, 0);
console.log(args)
结果,当我运行node
exlearnyonode.js 12 4 6
时,我得到了0作为和,但我希望22在您的代码中,假设a
是累加器,b
是集合中的元素,c
是元素的索引。相反,您应该只向传递两个参数,第一个是累加器,第二个是从collectionprocess.argv
生成的元素;它不提供相对于集合的索引
这应该做到:
console.log(process.argv.slice(1).reduce((acc, a) => acc + a))
slice(1)
将给出除第一个以外的参数:
var arr=[0,3,2,1]
控制台日志(arr.slice(1))
console.log(arr.slice(1).reduce((acc,a)=>acc+a))