如何改变代码使之输出[1, 4, 9]?

新手上路,请多包涵

代码如下:
期望输出[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.9k
3 个回答
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)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题