我正在尝试从 ES class 参数创建一个数组,但我得到的是一个空数组,为什么?

I'm trying to create an array from ES class arguments but I'm getting an empty Array, why?

考虑在这个 ES class 中创建值为“sideLength”的数组和“sides”时间的数组的这种情况的代码,但我一直得到一个空数组!!这是codepenlink

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);

不是这个

sides_array = sides_array.push(this.sideLength);

因为 Array.push() 没有 return 任何东西。

您正在为变量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());