【问题标题】:I'm trying to create an array from ES class arguments but I'm getting an empty Array, why?我正在尝试从 ES 类参数创建一个数组,但我得到一个空数组,为什么?
【发布时间】:2020-10-18 16:53:39
【问题描述】:

考虑在这个 ES 类中创建一个值为“sideLength”和“sides”时间的数组的场景的这段代码,但我一直得到一个空数组!这是codepen link

class ShapeNew {
  constructor(name, sides, sideLength) {
    this.name = name;
    this.sides = sides;
    this.sideLength = sideLength;
  }
  tryArray() {
    let sides_array = [];
    for (let i = 0; i < this.sides; i++) {
      sides_array = sides_array.push(this.sideLength);
    }
    return sides_array;
  }
  newPerimeter() {
    let peri = this.tryArray();
    console.log(peri.reduce((sum, accum) => sum + accum));
  }
}
let new_square = new ShapeNew("square", 4, 5);
new_square.newPerimeter();

我要做的就是将 4 转换为 [5,5,5,5],我该怎么做?

在此先感谢您对此进行调查,非常感谢 :)

【问题讨论】:

  • sides_array.push(this.sideLength); 而不是在每一轮都重新定义数组。
  • @Teemu 很简单,谢谢 :) 可以改进吗,例如,不使用局部变量而不是使用 args?
  • return new Array(4).fill(this.sideLength); 可以在没有任何变量的情况下解决问题。
  • @abappy 方法tryArray() 的目的是什么?它只是返回一个边长一样多的新数组
  • @Teemu 是的,但你为什么要将项目数硬编码为 4?它应该是动态的

标签: javascript arrays class args


【解决方案1】:

你想要这个

sides_array.push(this.sideLength);

不是这个

sides_array = sides_array.push(this.sideLength);

因为Array.push() 不返回任何内容。

【讨论】:

  • 因为 Array.push() 不返回任何内容。 不完全正确,Array.push() 返回数组的新长度
  • @SaymoinSam 谢谢你的澄清。它帮助我清楚地理解了:)
【解决方案2】:

您将推送新元素的返回值分配给变量sides_array,这是新长度,而不是每次都推送元素

class ShapeNew {
  constructor(name, sides, sideLength) {
    this.name = name;
    this.sides = sides;
    this.sideLength = sideLength;
  }
  tryArray() {
    let sides_array = [];
    for (let i = 0; i < this.sides; i++) {
      sides_array.push(this.sideLength);
    }
    return sides_array;
  }
  newPerimeter() {
    let peri = this.tryArray();
    console.log(peri.reduce((sum, accum) => sum + accum));
  }
}
let new_square = new ShapeNew("square", 4, 5);
new_square.newPerimeter();

但我想知道,如果你想做的只是计算周长,那你为什么不把边乘​​以边长呢?!

class ShapeNew {
  constructor(name, sides, sideLength) {
    this.name = name;
    this.sides = sides;
    this.sideLength = sideLength;
  }
  perimeter() {
    return this.sideLength * this.sides;
  }
}

let new_square = new ShapeNew("square", 4, 5);
console.log(new_square.perimeter());

【讨论】:

  • 是的,你完全正确 :) 我本来可以的,再次感谢这种新方法 :)
猜你喜欢
  • 1970-01-01
  • 2021-11-25
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
相关资源
最近更新 更多