+ Operator number in JavaScript

Source: Internet
Author: User

In some frameworks, I saw a similar way: + new Date (); I felt a little strange. I checked the relevant information and some help from some netizens. the usage is explained as follows, hoping to help you,Please correct me if this is not suitable.!

1. For reference type objects (I mean String, Date, Object, Array, Function, Boolean), The + operator operation process is as follows!
1. First, call the valueOf method of this object to obtain the returned value.
2. Convert the value A to A number to obtain the final value.

My tests are as follows:

Function w (s ){
Document. writeln ("<br/> ");
Document. writeln (s );
Document. writeln ("<br/> -----------------------------");
}
String. prototype. valueOf = function () {return 1 ;};
W (+ new String ("sss"); // output 1
String. prototype. valueOf = function () {return "";};
W (+ new String ("sss"); // output NaN

Date. prototype. valueOf = function () {return 1 ;};
W (+ new Date (); // output 1
Date. prototype. valueOf = function () {return "";};
W (+ new Date (); // output NaN

Object. prototype. valueOf = function () {return 1 ;};
W (+ {}); // output 1
Object. prototype. valueOf = function () {return "";};
W (+ {}); // output NaN

Array. prototype. valueOf = function () {return 1 ;};
W (+ []); // output 1
Array. prototype. valueOf = function () {return "";};
W (+ []); // output NaN

Var s = function (){};
Function. prototype. valueOf = function () {return 1 ;};
W (+ s); // output 1
Function. prototype. valueOf = function () {return "";};
W (+ s); // output NaN

Boolean. prototype. valueOf = function () {return 1 ;};
W (+ new Boolean (); // output 1
Boolean. prototype. valueOf = function () {return "";};
W (+ new Boolean (); // output NaN

2. For the basic data type, the value is converted to a number.
W (+ 5); // output 5
W (+ true); // output 1
W (+ false); // output 0
W (+ "ss"); // output NaN
W (+ "111"); // output 111

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.