Javascript学习(一)——数据类型

数据类型

1、基本类型(值)类型

  • string:任意字符串
  • number:任意数字
  • boolean:true/false
  • undefined:undefined
  • null:null

2、对象(引用)类型

  • Object:任意对象
  • Function:一种特别的对象(可执行)
  • Array:一种特别的对象(数值下标,内部数值是有序的)

3、判断数据类型

  • typeof:返回数据类型的字符串表达,用于判断数值/undefined/字符串/布尔值/function。无法区分null和object,array和object。
var a;
console.log(typeof a, typeof a==='undefined', a===undefined) // 'undefined' true true
console.log(undefined === 'undefined') // false
console.log(typeof null) // 'object'

var b = 1
var c = 's'
console.log(typeof a === 'number', typeof b ==='string');	// true true
  • instanceof:判断对象的具体类型
var b1 = {
  b2: [1, 'abc', console.log],
  b3: function() {
    console.log('b3')
  }
}

console.log(b1 instanceof Object, b1 instanceof Array);	// true false
console.log(b2.b2 instanceof Array, b1.b2 instanceof Object);  // true true
console.log(b1.b3 instanceof Function, b1.b3 instanceof Object);  // true true
console.log(typeof b1.b3 === 'function')  // true
console.log(typeof b1.b2[2] === 'function') // true
  • === : 判断undefined,null

4、相关问题

undefined和null的区别?

undefined代表定义未赋值,null定义并赋值,只是值为null。

var a;
console.log(a);  // undefined
a = null;
console.log(a); // null 

什么时候给变量赋值为null?

  • 初始赋值,表明将要赋值的对象
  • 结束前,让对象成为垃圾对象(被垃圾回收器回收)

严格区别变量类型与数据类型?

  • 数据的类型:基本类型、对象类型
  • 变量类型。基本类型:保存基本类型的数据。引用类型:保存的是地址值
发布了80 篇原创文章 · 获赞 135 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_37954086/article/details/101230397