最近看到这么一道题
如何让下面的代码执行:
const a = [1, 2, 3, 4, 5];
// Implement this
a.multiply();
console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]
执行结果: a.multiply is not a function
解决方式
在原型链上加 multiply 方法
Array.prototype.multiply = function () {
this.forEach((ele) => {
this.push(Math.pow(ele, 2));
});
};
在原型链上添加此方法之后的执行效果如下
console.log(a);// [1, 2, 3, 4, 5]
a.multiply();
console.log(a);// [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]