Home>

Follow me about implicit coercion of javascript,Interested friends can learn

Javascript data types are divided into six types,null, undefined, boolean, string, number, object.

object is a reference type,The other five are basic or primitive.We can use the typeof method to print which type a certain belongs to.To compare different types of variables, you must first convert the type.Called type conversion,Type conversion is also called implicit conversion.Implicit conversions usually occur when operators add, subtract, multiply and divide,Equal to, and less than,Greater than etc. .

typeof "11" //string
typeof (11) //number
"11"<4 //false

First, the conversion of basic types

Let's talk about addition, subtraction, multiplication and division first:

String plus number,The numbers are converted into strings.

2. Subtract strings from numbers,String to number. If the string is not a pure number, it will be converted to nan. The same is true for strings minus numbers.Subtraction of two strings is also converted to numbers first.

3. The same applies to multiplication, division, greater than, less than and less than conversion.

//implicit conversion +-* == /
//+
10 + "20" //"2010"
//-
10-"20" //-10
10-"one" //nan
10-"100a" //nan
//*
10 * "20" //200
"10" * "20" //200
///
20/"10" //2
"20"/"10" //2
"20"/"one" //nan

4. The order of addition operations is sensitive

Mixed expressions like this are sometimes confusing,Because javascript is sensitive to the order of operations.For example, the expression:1 + 2 + "3";//"33"

Since the addition operation is left-associative (that is, left-associative law), it is equivalent to the following expression:(1 + 2) + "3";//"33"

opposite of this,Expression:1+ "2" +3;//"123"The result is the string "123". The left-association law is equivalent to wrapping the addition operation on the left side of the expression in parentheses.

5. Take a look at a set of == again

1) .undefined equals null

2). When comparing strings and numbers,String to number

3). When the numbers are Boolean comparison,Boolean to Number

4). When comparing strings and booleans,Both to Digital

//==
undefined == null;//true
"0" == 0;true //true, string to number
0 == false;//true, boolean to number
"0" == false;//true, both numbers
null == false;//false
undefined == false;//false

7 false values:false, 0, -0, "", nan, null, and undefined, all other values ​​are truth

6, nan, not a number

nan is a special value,Explain that the results of some arithmetic operations (such as finding the square root of a negative number) are not numbers.The methods parseint () and parsefloat () return this value if they cannot parse the specified string.For some functions that return significant numbers in the general case,You can also use this method,Use number.nan to explain its error condition.

math.sqrt (-2)
math.log (-1)
0/0
parsefloat ("foo")

For many javascript beginners,Its first pitfall is that when you return a typeof, the result is usually unexpected:

console.log (typeof nan);//"number"

In this case,nan does not mean a number,Its type is numeric.Understand??

Because typeof returns a string,There are six types:"number", "string", "boolean", "object", "function", "undefined

keep cool,Because there is still a lot of confusion below.Let's compare two nans:

var x=math.sqrt (-2);
var y=math.log (-1);
console.log (x == y);//false

Maybe this is because we are not using strict equivalence (===) operations?Obviously not.

var x=math.sqrt (-2);
var y=math.log (-1);
console.log (x === y);//false

How about comparing two nans directly?

console.log (nan === nan);//false

Because there are many ways to represent a non-number,So one non-number will not be equal to another non-number that is nan,It still makes sense.

But of course,The solution is now there.Let's get to know the global function isnan:

console.log (isnan (nan));//true

Alas, but isnan () also has many flaws of its own:

console.log (isnan ("hello"));//true
console.log (isnan (["x"]));//true
console.log (isnan (()));//true

This has led to many different solutions.One of them is using the non-reflective nature of nan (for example, see kit cambridge's note)

var my={
 isnan:function (x) {return x! == x;}
}

Fortunately,In the upcoming ecmascript 6, there is a number.isnan () method that provides reliable detection of nan values.

in other words,Returns true only if the argument is true nan

console.log (number.isnan (nan));//true
console.log (number.isnan (math.sqrt (-2)));//true
console.log (number.isnan ("hello"));//false
console.log (number.isnan (["x"]));//false
console.log (number.isnan ((}));//false

Conversion of reference types

The comparison between the basic types is relatively simple.The comparison of reference types and basic types is relatively complicated,First you need to convert the reference type to a basic type.Compare again as described above.

1. Reference type to boolean is all true.

Like an empty array,Any object is a reference type,So [] is true. To convert a reference type to a number or a string, use valueof () or tostring ();the object itself inherits valuof () and tostring (), and you can also customize valueof () and tostring (). Use the inherited valueof () to convert to a string according to different objects.Numbers or itself,The object must be converted to a string using tostring.Normal objects call valueof () by default.

1). When the object turns to a number,Call valueof ();

2). When the object is converted to a string,Call tostring ();

Take a look at the following example:

0 == [];//true, 0 == [] .valueof ();--->0 == 0;
"0" == [];//false, "0" == [] .tostring ();--->"0" == "";
2 == ["2"];//true, 2 == ["2"]. Valueof ();--->2 == "2" --->2 == 2;
"2" == [2];//true, "2" == [2] .tostring ();--->"2" == "2";
[] ==! [];//true, [] .valueof () ==! boolean ([])->0 == false --->0 == 0;

When the object is turned into a number,The valueof () is called, and before that is called tostring ();so I guess the valueof method is like this.So the above example 0 == [] is more reasonable to change to the following.anyway,[] Finally turned to 0.

var valueof=function () {
 var str=this.tostring ();//tostring () is called first and converted to a string
 //...
}
0 == [];//true, 0 == [] .valueof ();->0 == "0"->0 == 0;

Custom valueof () and tostring ();

Both custom valueof () and tostring () exist, and valueof () will be called by default If there is only tostring (), then tostring () is called;
var a=[1];
a.valueof=function () {return 1;}
a.tostring=function () {return "1";}
a + 1;//2, valueof () is called first

Removing valueof () will call tostring ().

var a=[1];
a.valueof=function () {return 1;}
a.tostring=function () {return "1";}
a + 1;//2, call valueof () first
//Remove valueof
delete a.valueof;
a + 1;//"11", call tostring ()

What happens if I return to other?

var a=[1];
a.valueof=function () {return;}
a.tostring=function () {return 1;};
1-a;//nan

Other objects call valueof () to different types:

var a=();
a.valueof ();//object ()
var a=[];
a.valueof ();//[] itself
var a=new date ();
a.valueof ();//1423812036234 number
var a=new regexp ();
a.valueof ();///(?:)/regular object

The comparison between reference types is a comparison of memory addresses,No implicit conversion is required,Not much to say here.

[] == [] //false address is different

var a=[];

b=a;

b == a //true

2. Explicit conversion

Explicit conversions are simpler,You can use the class as a method to convert directly.

number ([]);//0

string ([]);//"

boolean ([]);//true

There are simpler conversion methods.

3 + "//string" 3 "

+ "3" //number 3

!! "3" //true

  • Previous Learn with me undefined and null of javascript
  • Next Explain how to parse and modify XML content in Python programs