代码如下:
期望输出[1, 4, 9]
const a = [1, 2, 3];
a.multiply();
console.log(a); // [1, 4, 9]
我是这么写的,还有更好的方法吗,
Array.prototype.multiply = function() {
const arr = this.map(item => Math.pow(item, 2));
this.length = 0;
this.push(...arr);
return this;
}
###Array.prototype.multiply = function() {
for(let i=0;i<this.length;i++){
this[i] **= 2;
}
}
我会这样写,不知道算不算你期望的更好
###Array.prototype.multiply = function() {
return this.map(i=>i*i)
}
###Array.prototype.multiply = function() {
this.forEach((item, i) => this[i] = item * item)
}