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

《你不知道的javascript(中)》1.1 类型 #26

Open
qunzi0214 opened this issue Feb 9, 2021 · 0 comments
Open

《你不知道的javascript(中)》1.1 类型 #26

qunzi0214 opened this issue Feb 9, 2021 · 0 comments
Labels
read book 读书笔记

Comments

@qunzi0214
Copy link
Owner

内置类型

  • 空值(null)
  • 未定义(undefined)
  • 布尔值(boolean)
  • 数字(number)
  • 字符串(string)
  • 对象(object)
  • 符号(symbol)

复习下字面量和构造初始化区别:boolean、string、number字面量与对应的内置对象不等同,null和undefined没有构造形式,而Object、Array、Function和RegExp无论使用字面量还是构造形式来声明,他们都是对象。同时,javascript在操作基本类型的时候自动将之转化为内置对象

可以用 typeof 操作符来查看值的类型
typeofnull 的处理有问题,但是这个bug由来已久,今后也未必会修复

typeof undefined   // 'undefined'
typeof true   // 'boolean'
typeof 42   // 'number'
typeof '42'   // 'string'
typeof {}   // 'object'
typeof Symbol()   // 'symbol'
typeof null   // 'object'

函数和数组都是 object 的子类型。函数是可调用对象,不仅如此,函数同样可以拥有属性

typeof [1, 2, 3] // 'object'

typeof function a (b, c) {} // 'function'

a.length // 2 (参数的个数)

值和类型

javascript中变量是没有类型的,只有值才有。变量在未持有值的时候是 undefined 。此时 typeof 返回 "undefined" 。而没有在作用域中声明的变量,是 undeclared 的(运行时会报错)。同时,typeof 有一个特殊的安全防范机制,可以使其对 undeclared 的变量进行操作时同样返回 undefined 而不报错,可以利用这个机制来处理变量是否存在的问题

var helper = (typeof doSomething !== 'undefined')
  ? doSomething
  : function() { /* do something */ }

helper()

还有一种方式是,通过全局对象 window 属性访问的方式来避免报错,只不过这种方式不适用于多 javascript 环境,因为此时无法保证全局对象是 window

var helper = window.doSomething
  ? window.doSomething
  : function() { /* do something */ }

helper()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
read book 读书笔记
Projects
None yet
Development

No branches or pull requests

1 participant