JavaScript基础(一) 数据类型

news/2024/7/3 1:53:05

动态类型

JavaScript 是一种弱类型或者说动态语言。这意味着你不用提前声明变量的类型,在程序运行过程中,类型会被自动确定。

数据类型

最新的 ECMAScript 标准定义了 7 种数据类型:

  • 6 种 原始类型:

    • Boolean

    • Null

    • Undefined

    • Number

    • String

    • Symbol (ECMAScript 6 新定义)

  • 和 Object

typeof 检测数据类型

typeof用来检测给定变量的数据类型,返回下列某个字符串

  • "boolean” --- 变量是布尔值(true/false)

  • "undefined" --- 变量未定义

  • "string" --- 变量是字符串

  • "number" --- 变量是数值

  • "function" --- 变量是函数

  • "object" --- 变量是对象或null

  • "symbol" --- 变量是Symbol

有这样一道题目,考察 typeof 返回值类型。

typeof(typeof(new Date()))   //string

但是在实际项目中,typeof 也只是用来判断变量是undefinedfunction。因为很多类型不能精确的判断出来,例如:

Valuefunctiontypeof
"foo"Stringstring
new String("foo")Stringobject
1.2Numbernumber
new Number(1.2)Numberobject
trueBooleanboolean
new Boolean(true)Booleanobject
new Date()Dateobject
new Error()Errorobject
[1,2,3]Arrayobject
new Array(1, 2, 3)Arrayobject
new Function("")Functionfunction
/abc/gRegExpobject
new RegExp("meow")RegExpobject
{}Objectobject
new Object()Objectobject
注意
typeof /s/ ===function; // Chrome 1-12 , 不符合 ECMAScript 5.1
typeof /s/ === object; // Firefox 5+ , 符合 ECMAScript 5.1

由上得出结论,当使用检测结果是objectfunction时,我们并不能看出实际的数据类型。

推荐使用 Object.prototype.toString(),结合call去实现对变量类型的精准判断。

Object.prototype.toString.call(null);      //”[object Null]”
Object.prototype.toString.call(undefined); //”[object Undefined]”
Object.prototype.toString.call(“abc”);     //”[object String]”
Object.prototype.toString.call(123);       //”[object Number]”
Object.prototype.toString.call(true);      //”[object Boolean]”

简单封装如下:

function _typeof(obj){if(typeof obj == object || typeof obj == function){var type =Object.prototype.toString.call(obj).split("")[1].toLowerCase();return type.match(/[a-z]/g).join("");  //正则去除字符串的]}return typeof obj; }

上面代码在标准浏览器中可以完全兼容,但是IE6(虽然现在不必兼容,也要了解下)中,却会出现以下问题:

_typeof(null);        //object
_typeof(undefined);   //object

原因在于IE6下

Object.prototype.toString.call(undefined);  //”[object Object]”
Object.prototype.toString.call(null);       //”[object Object]”

所以要先添加判断,使用String()对象将 undefinednull转为字符串。代码如下:

   function _typeof (obj){//注意到这里是 == 而不是 === ,//undefined 值是派生自 null 值的,所以null == undefined 返回true if(obj == null){return String(obj)}if(typeof obj == "object"; || typeof obj == "function"){var type =Object.prototype.toString.call(obj).split(" ")[1].toLowerCase();return type.substring(0,type.length-1); }return typeof obj; }

String()函数遵循下列转换规则:
如果值有 toString()方法,则调用该方法(没有参数)并返回相应的结果;
如果值是 null,则返回"null";
如果值是 undefined,则返回"undefined"

这样对 typeof 的扩展就封装好了。代码还有优化空间,这里不再继续。

Jquery已经实现了类型检测的封装,jquery.type()的内部实现如下:

//实例对象是能直接使用原型链上的方法的
var class2type = {};
var toString = class2type.toString;jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {class2type[ "[object " + name + "]" ] = name.toLowerCase();
});$.type = function( obj ) {//如果是null或者undefined,直接转成String返回//注意到这里是==而不是===,//undefined 值是派生自 null 值的,所以null == undefined 返回true if ( obj == null ) {return String( obj );}//当typeof 返回 object或function, 进入core_toString return typeof obj === "object" || typeof obj === "function" ?class2type[ core_toString.call(obj) ] || "object":typeof obj;
}

Undefined

Undefined 类型只有一个值,即特殊的 undefined。在使用 var 声明变量但未对其加以初始化时,这个变量的值就是 undefined,例如:

var foo;
alert(foo == undefined);  //true

undefined表示"缺少值",就是此处应该有一个值,但是还没有定义。
典型用法是:

  1. 变量被声明了,但没有赋值时,就等于 undefined

  2. 调用函数时,应该提供的参数没有提供,该参数等于 undefined

  3. 对象没有赋值的属性,该属性的值为 undefined

  4. 函数没有返回值时,默认返回 undefined

var name;
alert(name) // undefinedfunction f(x){console.log(x)}
f() // undefinedvar  o = new Object();
alert(o.p) // undefinedvar x = f();
alert(x) // undefined

Null

Null 类型是第二个只有一个值的数据类型,这个特殊的值是 null
如果定义的变量准备在将来用于保存对象,那么最好将该变量初始化为 null

null 有时会被当作一种对象类型,但是这其实只是语言本身的一个bug,即对 null 执行 typeof null 时会返回字符串"object"

原理是这样的,不同的对象在底层都表示为二进制,在JavaScript中二进制前三位都为0的话会被判断为object类型,null的二进制表示是全0,自然前三位也是0,所以执行 typeof 时会返回“object”。——《你不知道的JavaScript》

使用null的情况:

1.DOM,试图获取一个不存在的元素返回一个null值,而不是undefined
2.初始化一个对象的值,一般设为null
3.通过分配null值,有效地清除引用,并假设对象没有引用其他代码,指定垃圾收集,确保回收内存。

var table = document.getElementById("table"); 
console.log(table);  // nullvar obj = null; //初始化对象window.onload = function(){var el = document.getElementById("id");var id = el.id; //解除循环引用el.onclick = function(){alert(id); }el = null; // 将闭包引用的外部函数中活动对象清除
}

Boolean

Boolean 类型是常用的一种类型,只有两个字面值:truefalse

注意:字面值区分大小写,True 和 False 不是 Boolean 值。

经常遇到就是其他数据类型转为boolean的问题,只要遵循一个原则:

当值为""(空字符串)、0NaNnullundefined 时,都转为false,其他情况都为true


http://lihuaxi.xjx100.cn/news/255249.html

相关文章

ospf路由汇总的目的

ospf路由汇总的目的减少网络中lsa传输的数量,减少网络中的变化,减少链路状态数据库,减少路由表,大大提高数据包查表转发的能力,能减少因为链路状态数据库的变化而引起的spf算法的重计算。转载于:https://blog.51cto.co…

又居家办公了,要签合同怎么办?

本篇文章暨 CSDN《中国 101 计划》系列数字化转型场景之一。 《中国 101 计划——探索企业数字化发展新生态》为 CSDN 联合《新程序员》、GitCode.net 开源代码仓共同策划推出的系列活动,寻访一百零一个数字化转型场景,聚合呈现并开通评选通道&#xff0…

LeetCode实战:螺旋矩阵 II

题目英文 Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. Example: Input: 3 Output: [[ 1, 2, 3 ],[ 8, 9, 4 ],[ 7, 6, 5 ] ]题目中文 给定一个正整数 n,生成一个包含 1 到 n^2 所有元素&#x…

你见过哪些目瞪口呆的 Java 代码技巧?

欢迎关注方志朋的博客,回复”666“获面试宝典来源:blog.csdn.net/zl1zl2zl3/article/details/85196627技术点开发工具BeanBean 的验证拥抱 lombok重构设计模式技能总结技术点本文不是一个吹嘘的文章,不会讲很多高深的架构,相反&am…

时评:大学徒见“大门”不见“大师”

日前,网上一个关于大学豪华校门排行的帖子,在社会上引起广泛关注,其中山东聊城大学校门被爆花了8000万元。面对记者采访,该大学宣传部长刘树山颇为气愤,认为有人损害学校声誉,并准备起诉。他说该校大门总共…

我在MIT人工智能研究实验室工作一年学到的 5 件事!

Datawhale干货 作者:刘冰一、Ailleurs,来源:AI科技评论编辑 | 陈彩娴Mike Ferguson ,麻省理工学院大脑和认知科学系 (MIT BCS) 担任研究软件工程师/ML工程师。专门研究 Brain-Score(一种衡量类脑 AI 的工具&#xff09…

JavaScript夯实基础系列(四):原型

在JavaScript中有六种数据类型:number、string、boolean、null、undefined以及对象,ES6加入了一种新的数据类型symbol。其中对象称为引用类型,其他数据类型称为基础类型。在面向对象编程的语言中,对象一般是由类实例化出来的&…

沃通免费SSL证书申请指南

我们在做一些exchange或lync项目的时候很多时候都会用到公网证书,比如:我们做exchange2013和Office 365混合部署,或者通过SEM暂存迁移或CEM直接转换迁移的时候都需要用到公网证书,下面为大家介绍1个免费的SSL证书及申请的方法,希望…