js高级学习第一天
01.数据类型
-
分类
基本(值)类型
*String:任意字符串
*Number:任意数字
*boolean:true/false
*undefined:undefined
*null:null
对象(引用)类型
Object:任意对象
Function:一种特别的对象(可以执行)
Array:一种特别的对象(有下标, 内部数据是有序的) -
判断
*typeof:
可以判断undefined、String、Number、boolean、function
不可以判断null和object、array和object(因为使用typeof判断的null和array都是object)
& 为什么对于基本类型的null 却返回了object呢
对于 null 来说,虽然它是基本类型,但是会显示 object,这是一个存在很久了的 Bug,为什么会出现这种情况呢?因为在 JS 的最初版本中,使用的是 32 位系统,为了性能考虑使用低位存储了变量的类型信息,000 开头代表是对象,然而 null 表示为全零,所以将它错误的判断为 object 。虽然现在的内部类型判断代码已经改变了,但是对于这个 Bug 却是一直流传下来。为了避免这种问题,我们可以通过 Object.prototype.toString.call(xx)进行判断类型
————————————————
版权声明:本文为CSDN博主「 古德」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_41969216/article/details/89966801
*instanceof:
可以判断出具体的数据类型
*===
可以判断undefined和null
02.代码
<script type="text/javascript">
//1. 基本
// typeof返回数据类型的字符串表达
var a
console.log(a, typeof a, typeof a==='undefined',a===undefined ) // undefined 'undefined' true(类型) true(值)
console.log(undefined==='undefined')
a = 4
console.log(typeof a==='number')
a = 'atguigu'
console.log(typeof a==='string')
a = true
console.log(typeof a==='boolean')
a = null
console.log(typeof a, Object.prototype.toString.call(a),a===null) // 'object' true
console.log('-----------------')
//2. 对象
var b1 = {
b2: [1, 'abc', console.log],
b3: function () {
console.log('b3')
return function () {
return 'xfzhang'
}
}
}
console.log(b1 instanceof Object, b1 instanceof Array) // true false
console.log(b1.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.b2, '-------') // 'object'
console.log(typeof b1.b3==='function') // true
console.log(typeof b1.b2[2]==='function')
b1.b2[2](4)
console.log(b1.b3()())
03.相关问题
-
unll和undefined的区别
undefined是定义未赋值的数据
null定义并赋值了,只是值为null -
什么时候给变量赋值为null
*初始赋值时,表示将要赋值为对象
*结束前,让对象成为l垃圾对象 -
严格区分变量类型和数据类型
*数据的类型
*基本数据
*对象数据*变量的类型
*基本类型:保存的是数据
*引用类型:保存的地址值
代码
<script type="text/javascript">
// 实例: 实例对象
// 类型: 类型对象
function Person (name, age) {// 构造函数 类型
this.name = name
this.age = age
}
var p = new Person('tom', 12) // 根据类型创建的实例对象
// Person('jack', 12)
// 1. undefined与null的区别?
var a
console.log(a) // undefined
a = null
console.log(a) // null
//起始
var b = null // 初始赋值为null, 表明将要赋值为对象
//确定对象就赋值
b = ['atguigu', 12]
//最后
b = null // (被垃圾回收器回收)
// b = 2
var c = function () {
}
console.log(typeof c) // 'function'
</script>
</body>
</html>