JavaScript 深入 数据类型

JavaScript 数据类型

1. 数据类型

弱类型特性

var num = 32;
num = "this is a string";

num 明明是number类型,为什么可以赋值成string

console.log(32 + 32)  // 64
console.log("32" + 32)  // 3232
console.log("32" - 32)  // 0

“32” 加上 32 等于 “3232”,相减却等于0。

原始类型

  • number

  • string

  • boolen

  • null

  • undefined

  • object

    • Function

    • Array

    • Date

    • ……

隐式类型转换

var x = 'The answer is ' + 42;
var y = 42 + ' is the answer';


"37" - 7  // 30
"37" + 7  // 377

巧用+/-规则转换类型 num - 0num - ''将num转换为number或者string

==

类型相同,同===

类型不同,尝试类型转换和比较:null == undefined

object == number|string 会尝试将对象转换为基本类型new String('hi') == 'hi'

"1.23" == 1.23
0 == false
null == undefined
new Object() == new Object()
[1, 2] == [1, 2]
===

类型不同,返回 false

null === null
undefined === undefined
NaNNaN
new Objectnew Object

包装对象

var str = "string";
var strObj = new String("string");
str  // "string"
strObj  // {0: "s", 1: "t" …… , length: 6, [[PrimitiveValue]]: "string"}

当我们打印str.length得到6,但它是一个基本类型不是对象为什么会有这样一个属性呢?

> str.t = 10
< 10
> str.t
< undefined

当我们将基础类型的值当作对象一样使用给他熟悉时,会智能的将基础类型转化为包装类型的临时对象,当完成访问以后,临时对象会被销毁掉。(123).toSting一样可以将123转为"123"。

类型检测

typeof
typeof 100  // "number"
typeof true  // "boolean"
typeof function  // "function"
typeof(undefined)  // "undefined"
typeof new Object()  // "object"
typeof [1, 2]  // "object"
typeof NaN  // "number"
typeof null  // "object"
instanceof

obj instanceof Object

[1, 2] instanceof Array === true
new Object() instanceof Array === false
Object.protype.toString
Object.prototype.toString.apply([]);  // "[object Array]";
Object.prototype.toString.apply(function(){});  // "[object Function]"
Object.prototype.toString.apply(null);  // "[object Null]";
Object.prototype.toString.apply(undefined);  // "[object Undefined]";
  • typeof 适合基本类型及 function 检测,遇到 null 失效

  • [[Class]] 通过 {}.toString拿到,适合内置对象和基本类型,遇到 null 和 undefined 失效

  • instanceof 适合自定义对象,也可以用来检测原生对象,在不同 iframe 和 window 间检测失效

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值