Analyze the JavaScript variable types in detail

  • 2020-07-21 06:46:28
  • OfStack

Variable types

There are only six: the four original data types boolean, number, string, undefine, and the other object,function are objects

typeof,instanceof

See examples directly:


    var obj = null;
    console.info(typeof obj);    //Object
    var arr = [];
    console.info(arr instanceof Object);  //true
    console.info(arr instanceof Array);  //true

Wrapper objects for raw data types (Wapper Object)

string,number,boolean all correspond to specific wrapper objects

Data type conversion

Use parseInt,parsetFolat to convert to numeric types


console.log(parseInt("34", 10)); //34
console.log(parseInt("34s5b", 10)); //34
console.log(parseInt("s", 10)); //NaN
console.log(parseInt(3.14, 10)); //3

javascript is a dynamically typed programming language. The same variable is the same type of data captured


//number
var value = 100;
//string
value = "qiu";
//object
value = [1, 'two', 3];

Variations of the "=" sign:

= assignment
= = sentence, etc
=== strictly judge etc


var x = 42;
var y = "42";
console.log(x == y) //true;
console.log(x === y) //false

undefined vs null

udefine: a variable is undefined and does not have a valid value.
null: nothing, a variable does not refer to any object. null is an object of type object (variable but no reference value)


var obj = null;
if (obj === null) {
alert("obj === null"); // This sentence will be executed 
}
else {
alert("obj!=null");
}
alert(typeof obj); //object

Judgment of undefine and null, etc


var myVar;
//true
console.log(typeof myVar === "undefined");
console.log(myVar === undefined);
var myVar2 = null;
console.log(typeof myVar2); //object
//true;
console.log(myVar2 == null);
console.log(myVar2 === null);
//true
console.info(myVar == myVar2); //undefine == null;  is true
//false
console.info(myVar === myVar2); //undefine === null;  is false

true and false

undefined, null,NaN,"",0
In addition to these values, the other values are true;

Operator:!! With the | |

!!!!! Convert the following expression to the boolean value and return true or false
!!"qiu" true
!!null false

||
var ns = ns || {}
Return {} if ns is not defined, otherwise return ns

Note: The variables must be var, otherwise the pit will fall! If you don't write var, it becomes a global variable

This is the end of this article, I hope you enjoy it.


Related articles: