面试题答案
一键面试兼容性问题
- 旧版本浏览器:在一些较旧的浏览器(如IE8及以下),直接给内置类(如
Array
)原型添加方法可能会导致兼容性问题。因为这些浏览器对内置对象原型的扩展支持不完善,可能会出现不可预料的错误,比如在IE8及以下,向Object.prototype
添加新属性或方法时,可能会影响到for...in
循环遍历对象属性的行为。 - 严格模式:在严格模式下,如果使用
eval
或with
等可能改变作用域链的语法,可能会导致新添加的方法行为异常。例如eval
内部创建的函数作用域与外部作用域对Array.prototype
的扩展认知可能不同。
常见解决思路
- 检测是否已存在该方法:
if (!Array.prototype.customSum) {
Array.prototype.customSum = function() {
return this.reduce((acc, val) => acc + val, 0);
};
}
这样可以确保在不同浏览器环境下,只有当Array.prototype
上不存在customSum
方法时才进行添加,避免覆盖已有的自定义实现。同时,使用reduce
方法计算数组元素之和是一种简洁且兼容性较好的方式,现代浏览器基本都支持reduce
,对于不支持的旧浏览器,可以先对Array.prototype
添加reduce
方法的垫片(polyfill),例如:
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(callback, initialValue) {
let accumulator;
let i;
if (initialValue === undefined) {
accumulator = this[0];
i = 1;
} else {
accumulator = initialValue;
i = 0;
}
for (; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
}
return accumulator;
};
}
然后再添加customSum
方法。