Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数据类型 #3

Open
K-Kevin opened this issue Sep 16, 2019 · 0 comments
Open

数据类型 #3

K-Kevin opened this issue Sep 16, 2019 · 0 comments

Comments

@K-Kevin
Copy link
Owner

K-Kevin commented Sep 16, 2019

截止到 ES6,JavaScript 一共有 7 个数据类型,ES5 中定义的 6 种分别是:Undefined、Null、Boolean、String、Number 和对象(Object)。

ES6 引入了一种新的数据类型 Symbol(在 ES6 中单独讲解)。

typeof 操作符

typeof 操作符用来检测给定变量的数据类型,返回字符串。

typeof 95; // number
typeof '123';//string
typeof true; //boolean
typeof undefined; //undefined
typeof new Function(); // function

typeof null 会返回 "object",因为特殊值 null 被认为是一个空对象引用。Safari 5 及之前的版本、Chrome 7 及之前的版本在对正则表达式调用 typeof 操作符会返回 "function",而其他浏览器在这种情况下会返回 "object"。

Undefined 类型

var message;//默认取得了 undefined

//var age; //这个没有声明

alert(message);	//"undefined"
alert(age);	//错误

对于未声明的变量,只能通过 typeof 操作符检测其数据类型。

不可靠的 undefined

通常我们判断一个变量是否是 undefined,一般这样写:

if(a === undefined){}

但 JavaScript 中的 undefined 并不可靠,例如:

function test(a) {
    var undefined = 1;
    console.log(undefined);	//=>1
    if(a === undefined) {
        //...
    }
}

因为 undefined 作为一个变量存在时,可以轻易的被修改,使用后对 undefined 的理解引起歧义。

最常见的用法是通过以下运算符来获得 undefined,表达式为 0 时的运算开销最小。

void 0; || void(0);	

Boolean

可以参考一下规则进行 boolean 判断。

数据类型 转换为 true false
Boolean true false
String 任意非空字符串 ""(空字符串)
Number 非 0 0、NaN
Object 任何对象 null
Undefined n/a(或 N/A) undefined

Object 类型

Object 的每个实例都具有下列属性和方法。

  • constructor:保存着用于创建当前对象的函数。
  • hasOwnProperty(propertyName):用于检查给定的数字能够在当前对象实例中(而不是在实例的原型中)是否存在。属性名propertyName必须以字符串形式指定。
  • isPrototypeOf(object):用于检查传入的对象是否是传入对象的原型。
  • propertyIsEnumerable(propertyName):用于检查给定的属性是否能够使用fofr-in语句来枚举。属性名propertyName必须以字符串形式指定。
  • toLocaleString():返回对象的字符串表示,该字符串与之相应环境的地区对应。
  • toString():返回对象的字符串表示。
  • valueOf():返回对象的字符串、数值或布尔值表示。通常与toString()方法的返回值相同。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant