简体   繁体   中英

CoffeeScript a = +a

I'm debugging through someone else's code and I found this snippet:

req.body.address.id = +req.body.address.id

My first thought was that this had to do with making a negative number positive, but it doesn't do that. The address id's in question here should always be numbers, and adding a + in front of a number doesn't seem to do anything.

Would anyone know why you'd do this?

The unary + operator converts the operand to a number. From MDN :

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

For example:

var a = '1';
console.log(a);  // "1"
console.log(+a); // 1 

So yes, it has no effect on numbers, but if you provide it a non-numeric value, it's useful for safely converting it to a number.

The unary + operator will perform type conversion, forcing the value ToNumber() , if necessary:

var foo = '1';
var bar = +foo;

console.log(typeof foo, foo + 2); // 'string' '12' (concatenates)

console.log(typeof bar, bar + 2); // 'number' 3 (adds)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM