# js当中的type(数据类型) #

You-Dont-Know-JS TYPE学习笔记

在es6版本后,js一共有七种类型他们非别是:

  • null
  • undefined
  • boolean
  • number
  • string
  • object
  • symbol

当然这其中有一个特殊的类型就是“null”

typeof null === 'object' //true

这是一个公认js的bug,但是考虑到众多页面的兼容性,这个bug至今没有被修改。

在JavaScript中,变量是没有类型的,值有类型。一个变量可以代表任何值。##

var a = 42;
typeof a; // "number"

a = true;
typeof a; // "boolean"

undefined 和 undeclared 的区别

如果一个变量没有被富裕值,那么这个值就是undefined

var a;

typeof a; // "undefined"

var b = 42;
var c;

// later
b = c;

typeof b; // "undefined"
typeof c; // "undefined"

大多数的开发者认为undefined和undeclared是同义词,但是他们差别非常大

undefined是一个变量被定义了,但还没有被赋值。而undeclared是没有定义的变量

var a;

a; // undefined
b; // ReferenceError: b is not defined

//而JavaScript的报错信息也经常能够迷惑开发者。

var a;

typeof a; // "undefined"

typeof b; // "undefined"

//而typeof操作符更是加重了这些困惑。

需要注意到,虽然b变量没有定义,但是被typeof操作符执行时,并没有报错

typeof 操作符的特殊用法。(检测变量是否存在)


// oops, this would throw an error!
if (DEBUG) {
    console.log( "Debugging is starting" );
}

// this is a safe existence check
if (typeof DEBUG !== "undefined") {
    console.log( "Debugging is starting" );
}

还有一种方法:

if (window.DEBUG) {
    // ..
}

if (!window.atob) {
    // ..
}

但是这种方法是大多数开发者所极力避免的,因为你的js代码可能运行在node中,node中是不存在window顶级对象的。

你可能感兴趣的:(# js当中的type(数据类型) #)