JavaScript日记
有关JavaScript常用的知识点.
数据类型
数值(number)
字符串(string)
布尔值(boolean)
undefined: 表示“未定义”或不存在,即由于目前没有定义,所以此处暂时没有任何值。null: 表示空值,即此处的值为空。对象(object): 各种值组成的集合。
Symbol:ES6新增,表示独一无二的值。
typeof运算符
typeof运算符可以返回一个值的数据类型。
其中空数组[]也返回object类型,这表示在JavaScript内部,数组本质上只是一种特殊的对象。
当然想要区分数组还是对象,可以使用instanceof运算符
null的数据类型也是object, 由于历史原因造成,为了兼容以前的代码
null,undefined和布尔值
null与undefined的区别:
+ `null`是表示一个空的对象,转为数值时为`0`
+ `undefined`是表示“此处无定义”的原始值,转为数值时为`NaN`代码示例:
Number(undefined) // NaN
Number(null) // 0在if语句中,null与undefined都会被自动转为false,相等运行符==直接报告两者相等。
if (!undefined){
console.log('undefined is false')
}
// result: undefined is false
if (!null){
console.log('null is false')
}
// result: null is false
undefined == null
// result: true布尔值
真:true
假:false
下列运算符会返回布尔值:
前置逻辑运算符:
!(Not)相等运行符:
===,!==,==,!=比较运算符:
>,>=,<,<=
下面六个值被转为false,其它值都视为true:
undefiendnullfalse0NaN""或''(空字符串)
空数组([])和空对象({})对应的布尔值,都是true
示例代码:
if (''){
console.log("true")
}
// result:不会有输出
if ([]) {
console.log('true');
}
//result: true