代码如下:
期望输出[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;
}
代码如下:
期望输出[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() {
this.forEach((item, i) => this[i] = item * item)
}
13 回答12.9k 阅读
8 回答2.7k 阅读
2 回答5.1k 阅读✓ 已解决
7 回答2.1k 阅读
5 回答1.3k 阅读
3 回答2.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
我会这样写,不知道算不算你期望的更好