Javascript map() forEach() 方法无法连续工作

Javascript map() forEach() method not working in succession

我知道这有点令人费解,但考虑一下这个假设:

class test {
    points = [[10,15]];
    rotate (angle){
        let deg = angle *= Math.PI/180; //degrees to radians
        this.points.map((point, pointIndex) => point.map((value, axis) => this.points[pointIndex][axis] = axis === 0 ? (this.points[pointIndex][0]*Math.cos(deg)-this.points[pointIndex][1]*Math.sin(deg)):(this.points[pointIndex][1]*Math.cos(deg)+this.points[pointIndex][0]*Math.sin(deg))));

        //This essentially maps the current points to their projections after rotating them by some angle
        //It performs two different operations respective to the two different values in the nested array
    }
}

let foo = new test;
foo.rotate(90);
console.log(foo.points);

运行 这将 return:

Array [ -15, -14.999999999999998 ]

为了论证,这不是预期的结果。

起初我以为这与“?”的使用有关。运算符,但删除它并将结果分离到它们自己的映射中:

class test {
    points = [[10,15]];
    rotate (angle){
        let deg = angle *= Math.PI/180;

        this.points.map((point, pointIndex) => this.points[pointIndex][0]=(this.points[pointIndex][0]*Math.cos(deg)-this.points[pointIndex][1]*Math.sin(deg)));

        this.points.map((point, pointIndex) => this.points[pointIndex][1]=(this.points[pointIndex][1]*Math.cos(deg)+this.points[pointIndex][0]*Math.sin(deg)));
        
    }
}

let foo = new test;
foo.rotate(90);
console.log(foo.points);

但这会导致相同的结果。但是,当 运行 任何一行本身时,由于它们被拆分,仅影响第一个或第二个元素,具体取决于被消除的元素,准确的结果是 returned:

Array [ -15, 15 ] (if the second line is removed) Array [ 10, 10.000000000000002 ] (if the first line is removed)

两者都是return各自索引的准确值。 ([ -15, 10.000000000000002 ] 是正确的,取第一个数组的第一个元素和第二个数组的第二个元素。)

出于某种原因,连续 运行 他们失败了。

提前致谢。

编辑:使用 forEach() 时会出现同样的问题。

您不应在转换中访问当前对象。

class test {
    points = [[10,15]];
    rotate (angle){
        let deg = angle * Math.PI/180; //degrees to radians
        this.points = this.points.map((point) => {
          let newPoint = [0,0];
          newPoint[0] = point[0]*Math.cos(deg)-point[1]*Math.sin(deg);
          newPoint[1] = point[1]*Math.cos(deg)+point[0]*Math.sin(deg);
          return newPoint
        })

        //This essentially maps the current points to their projections after rotating them by some angle
        //It performs two different operations respective to the two different values in the nested array
    }
}

let foo = new test;
foo.rotate(90);
console.log(foo.points);

您正在变换一个坐标,然后使用新值(而不是您应该使用的旧值)对另一个坐标进行操作。我认为这就是问题所在。

class test {
    points = [[10, 15]];

    rotate (angle){
        let radians = (Math.PI / 180) * angle,
          cos = Math.cos(radians),
          sin = Math.sin(radians);
          
        this.points = this.points.map((p) => {
          return [cos * p[0] + sin * p[1], cos * p[1] - sin * p[0]];
        })
    }
}

let foo = new test;
foo.rotate(90);
console.log(foo.points);

Link to jsFiddle