JavaScript的十个独特特性与隐藏机制
数据类型特性
1. Null的类型矛盾
JavaScript中null表示空值,但类型检测却返回对象:
console.log(typeof null); // 输出 'object'
但null并非对象实例:
console.log(null instanceof Object); // 输出 false
2. NaN的数值身份
NaN表示非数值,但其类型为数值且不等于自身:
console.log(typeof NaN); // 输出 'number'
console.log(NaN === NaN); // 输出 false
需使用isNaN()进行检测。
3. 空数组的布尔转换
空数组在比较中表现为false:
console.log([] == false); // 输出 true
但在布尔上下文中为true:
if ([]) console.log('执行'); // 输出 '执行'
建议使用严格相等避免隐式转换:
console.log(0 === false); // 输出 false
正则表达式特性
4. 动态替换函数
replace()支持回调函数实现高级替换:
const result = '10 20 30'.replace(/\d+/g, num =>
parseInt(num) > 15 ? 'X' : num
);
console.log(result); // 输出 "10 X X"
5. 正则方法扩展
test()方法高效验证匹配:
console.log(/\w{4}/.test('code')); // 输出 true
动态构建正则表达式:
function matchTerm(term, str) {
return str.match(new RegExp(`\\b${term}\\b`, 'gi'));
}
函数作用域机制
6. 动态绑定作用域
使用call()改变函数上下文:
function showValue() {
console.log(this.val);
}
const obj = { val: 42 };
showValue.call(obj); // 输出 42
7. 立即执行函数
自执行函数隔离变量作用域:
let data = '初始值';
setTimeout((function(val) {
return () => console.log(val);
})(data), 100);
data = '修改值'; // 仍输出 '初始值'
浏览器差异问题
8. 颜色格式差异
Firefox返回RGB格式颜色值:
const elem = document.getElementById('element');
const color = window.getComputedStyle(elem).color;
// Firefox: 'rgb(255, 0, 0)',Chrome: '#ff0000'
数值处理特性
9. 浮点数精度问题
二进制浮点数导致精度误差:
console.log(0.15 + 0.15 === 0.3); // 输出 true
console.log(0.1 + 0.2 === 0.3); // 输出 false
建议使用容差范围比较:
const diff = Math.abs((0.1 + 0.2) - 0.3) < 1e-10;
10. undefined的可变性
undefined不是保留字,可被覆盖:
let testVar;
console.log(testVar === undefined); // 输出 true
undefined = '已定义';
console.log(testVar === undefined); // 输出 false
函数参数可保护原始undefined:
(function(_, undefined) {
console.log(undefined); // 原始undefined
})();