概述

JavaScript严格来说总有六中属性值:

  • number
  • string
  • boolen
  • underfined
  • null
  • object

object又分为三类:

  • 狭义的对象
  • Array 数组
  • function 函数
    在js中,function是一个数据类型,他可以被赋值给变量,这是非常特殊的一个点。
1
2
3
4
5
const addNum = (a,b) => {
return a+b
}

addNum(1,2) //3

本文会先介绍null,undefined,boolen,其余在后续的小节介绍。

Typeof

判断数据的类型有三种方法:

  1. typeof
  2. instanceof
  3. Object.prototype.toString

typeof会返回的值为number,string,boolen,undefined,function

null返回的是object,数组返回的也是object

1
2
3
typeof null // "object"

typeof [] // "object"

null与undefined

和常识不同,一个变量是可以被赋值为undefined

1
2
3
let num = undefined;

console.log(typeof num); // undefined

nullundefined都可以表示没有,语法没有任何区别,在==中也表现为相等,在if中都表示false

1
2
3
4
5
6
7
8
9
10
11
12
if (!undefined) {
console.log('undefined is false');
}
// undefined is false

if (!null) {
console.log('null is false');
}
// null is false

undefined == null
// true

但是两者转化的时候不同:

  • undefined 转化为 NaN
  • null 转化为0
1
2
3
4
let num = undefined;
let num2 = null;
console.log(Number(num)); // NaN
console.log(Number(num2)); // 0

具体理解,undefined表示未定义,null表示为当前值为空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 变量声明了,但没有赋值
var i;
i // undefined

// 调用函数时,应该提供的参数没有提供,该参数等于 undefined
function f(x) {
return x;
}
f() // undefined

// 对象没有赋值的属性
var o = new Object();
o.p // undefined

// 函数没有返回值时,默认返回 undefined
function f() {}
f() // undefined

布尔值

布尔值只有truefalse两个值

在期望得到布尔值的情况下,会自动将一些值转化为布尔值

以下值都被转化为false:

  • undefined
  • null
  • false
  • 0
  • NaN
  • ""或者''

其他的值都被转化为true

1
2
3
4
5
6
7
8
9
if ([]) {
console.log('true');
}
// true

if ({}) {
console.log('true');
}
// true