我试图弄清楚为什么我的表不会通过求和函数运行

时间:2019-04-24 13:32:09

标签: javascript

我正在尝试通过求和函数放置表格,但是该函数未将其中的任何值视为数字

我试图更改表的设置方式和值,但是我尚未实现目标

class Vector2{
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.X = x;
        this.Y = y;
    }
}

function Sum(a, start, end){
    let s = 0;
    for(i = start; i <= end; i++){
        s += a[i];
    }
    return s;
}


const v1 = new Vector2(1, 2);
const v2 = new Vector2(-1, 1);
const v3 = new Vector2(-1, -1);
const v4 = new Vector2(1, -1);


var arrX = [v1, v2, v3, v4];


//var sx = Sum(arrX, 0, 3);
//var sy = Sum(arrY, 0, 3);

//var X = (1/arrX.length)*Sum(arrX, 0, 3);
//var Y = (1/arrY.length)*Sum(arrY, 0, 3);

//console.log(X, Y);

function init(){
    var x = [];
    var y = [];
    var cx = 0;
    var cy = 0;
    for(i = 0; i < arrX.length; i++){
        x[i] = arrX[i].x;
        console.log(Sum(x, 0, 3));
    }
}

init();

2 个答案:

答案 0 :(得分:0)

在此块中,您每次向数组添加项目时都要对数组求和。

for(i = 0; i < arrX.length; i++){
    x[i] = arrX[i].x;
    console.log(Sum(x, 0, 3));
}

您应该在数组填充后求和。

for(i = 0; i < arrX.length; i++){
    x[i] = arrX[i].x;
}
console.log(Sum(x, 0, 3));

答案 1 :(得分:0)

如果要对数组中对象的各个属性(例如'x')求和,则应将该属性作为求和函数的参数。以下作品:

const sumAttribute = (my_array,att) => my_array.reduce((a,c) => a+c[att],0); 

该属性需要以字符串形式传递。例如:

class Vector2{
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.X = x;
        this.Y = y;
    }
}

const sumAttribute = (my_array,att) => my_array.reduce((a,c) => a+c[att],0);

const v1 = new Vector2(1, 2);
const v2 = new Vector2(-1, 1);
const v3 = new Vector2(-1, -1);
const v4 = new Vector2(1, -1);


var arr = [v1, v2, v3, v4];

console.log(sumAttribute(arr,'x'));
console.log(sumAttribute(arr,'y'));