简体   繁体   English

我试图从 ES 类参数创建一个数组,但我得到一个空数组,为什么?

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

Consider this code for this scenario of creating an Array with value of "sideLength" and for "sides" times within this ES class, but I'm keep getting an empty array!!考虑此代码,用于在此 ES 类中创建一个值为“sideLength”的数组和“边”时间的数组,但我一直得到一个空数组!! here is codepen link这是codepen链接

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

All I'm trying to do is convert 4 into [5,5,5,5], how do I do that?我想要做的就是将 4 转换为 [5,5,5,5],我该怎么做?

Thanks in advance for looking into this, I appreciate it :)提前感谢您对此进行调查,我很感激:)

You want this你要这个

sides_array.push(this.sideLength);

Not this不是这个

sides_array = sides_array.push(this.sideLength);

Because Array.push() does not return anything.因为Array.push()不返回任何内容。

You are assigning to the variable sides_array the returned value of pushing a new element which is the new length, instead just push the element each time您正在为变量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();

But I was wondering, if all what you wanted to do is just calculating the perimeter, then why don't you just multiply the sides with side length?!但我想知道,如果你想做的只是计算周长,那你为什么不把边乘​​以边长呢?!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM