How does this alternative to a for loop iteration work? (Javascript)
This question already has an answer here:
let args = process.argv <- That gets the arguments let sum = args.reduce(function(acc, curr) { <- that uses array reduce, which reduces it to a single value return +acc + +curr; <- this uses a unary operator to convert both into a numeric representation then adds them
console.log(sum) <- that consoles out the returned value from array.reduce which is then assigned to sum.
reduce documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
unary operator documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus
As far as best practice is concerned, I don't believe that this is extremely readable. And its not a common idiom in JS. Due to type coercion, very rarely would you need this. That being said, I don't think its bad practice.
链接地址: http://www.djcxy.com/p/73934.html上一篇: javascript:在变量前加上符号
