js基础

来源:互联网 发布:孕妇枕 知乎 编辑:程序博客网 时间:2024/05/17 02:13

js数据类型

5种不同的数据类型:string、number、boolean、object、function
3种对象类型:Object、Data、Array
2种不含任何值的数据类型:null、undefined

typedef操作符

可以使用typedef操作符查看javascript变量类型;
但是如果对象是JavaScript Array或者JavaScript Data,无法通过typedef判断类型,返回的都是Object。

可以使用constructor属性来判断,该属性返回所有JavaScript变量的构造函数;
实例:

"John".constructor                 // 返回函数 String()  { [native code] }(3.14).constructor                 // 返回函数 Number()  { [native code] }false.constructor                  // 返回函数 Boolean() { [native code] }[1,2,3,4].constructor              // 返回函数 Array()   { [native code] }{name:'John', age:34}.constructor  // 返回函数 Object()  { [native code] }new Date().constructor             // 返回函数 Date()    { [native code] }function () {}.constructor         // 返回函数 Function(){ [native code] }

1、判断对象是否为数组(包含字符串”Array”):

function isArray(myArray) {    return myArray.constructor.toString().indexOf("Array") > -1;}

2、判断对象是否为日期(包含字符串”Data”):

function isDate(myDate) {    return myDate.constructor.toString().indexOf("Date") > -1;}

JavaScript把undefined、null、NaN、0和空字符串” “视为false,其他的值视为true。

原创粉丝点击