Some of the magic of the plus sign of + operator in javascript

  • 2020-03-30 03:12:52
  • OfStack

Javascript is a magical language, and there's a magical additive operator in a non-magical language.

Common adder operators we can use to do:

1. Addition operation, e.g. Alert (1+2); = = > 3
2. String concatenation, e.g. Alert (" a "+" b "); = = >" Ab"

A bit more advanced still have "+=", also do above two kinds of operation.

Yesterday in the javascript jungle group asked a question: how do you convert the date format string "2000-09-11 19:22" to a number of milliseconds?

Cut dream people immediately answer me everyday: + new Date (' why do '2000-09-11) and not tried it on, the correct should be + new Date (' 2000/09/11 why do').

The answer doesn't seem to matter anymore, you see the plus operator in front of it, which I honestly haven't seen before. The magic javascript plus operator, but also very magical function, conversion data types, generally is the conversion of strings and values, for example, javascript forest user Jason gave an example:


//Hexadecimal conversion:
+ " 0xFF " ;              // -> 255
//Get the current timestamp, equivalent to 'new Date().gettime ()' :
+new Date();
//ParseFloat ()/parseInt(
parseInt( " 1,000 " );    // -> 1, not 1000
+ " 1,000 " ;             // -> NaN, much better for testing user input
parseInt( " 010 " );      // -> 8, because of the octal literal prefix
+ " 010 " ;               // -> 10, `Number()` doesn't parse octal literals
//Some simple abbreviations such as: if (someVar === null) {someVar = 0};
+null;                // -> 0;
//Boolean to integer
+true;                // -> 1;
+false;               // -> 0;
//Other:
+ " 1e10 " ;              // -> 10000000000
+ " 1e-4 " ;              // -> 0.0001
+ " -12 " ;               // -> -12 : 

Of course, the operation of adding a number to an empty string can turn a number into a string, for example: alert(typeof (1+ "")); / / - > The string;

Also included is a minus operator that converts a string to a number, such as alert(typeof (" 123 "-0)); / / - > Number;

Of course, there may be some unknown use of the operator, welcome to add comments!


Related articles: