您的位置:首页 > Web前端 > JavaScript

JavaScript基础(一)--数据类型

2017-09-23 18:30 465 查看
一、六种数据类型

原始类型:object、number、string、Boolean、null、undefined

二、隐式转换

1、+和-

var x='The answer is'+42;
var y=43+'is the answer';
if(x==y){
console.log(x!=y)
}else{
console.log(x==y)
}




[Web浏览器] “false”

2、类型转换





console.log(“1.23”==1.23);//true

console.log(0==false); //true

console.log([1,2]==[1,3]); //false

console.log(null==undefined); //true

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

console.log((new Object)===(new Object));//false

console.log(null===null);//true

console.log(null===undefined); //false

console.log(undefined===undefined); //true



类型相同,同===

类型不同,尝试类型转换和比较:

null == undefined 相等

number == string 转number 1 == “1.0” // true

boolean == ? 转number 1 == true // true

object == number | string 尝试对象转为基本类型 new String(‘hi’) == ‘hi’ // true

其它:false

三、包装对象

Object 对象:Function、Array、Date、Number。。。

四、类型检测

typeof

instanceof

Object.prototype.toString

constructor

duck type

typeof



console.log(typeof 100);//number

console.log(typeof true); //boolean

console.log(typeof function(){}); //function

console.log(typeof (undefined)); //undefined

console.log(typeof new Object()); //Object

console.log(typeof [1,2]); //object

console.log(typeof NaN); //number

console.log(typeof null); //object

console.log(typeof null === “object”); //true

obj instanceof Object



var a=([1,2] instanceof Array===true);

console.log(a); //true

var b=(new Object() instanceof Array ===false);

console.log(b); //true

Object.prototype.toString



Object.prototype.toString.apply([]) //===”[Object Array]”

Object.prototype.toString.apply(function(){}) //===”[Object Function]”

Object.prototype.toString.apply(null) ///===”[Object Null]”

Object.prototype.toString.apply(undefined) ///===”[Object Object]”

typeof:适合基本类型及function检测,遇到null失效。

[[Class]]:通过{}.toString拿到,适合内置对象和基元类型,遇到null和undefined失效(IE678等返回[object Object])。

instanceof:适合自定义对象,也可以用来检测原生对象,在不同iframe和window间检测时失效。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 数据