mardi 13 février 2018

2nd if-condition in for-loop does not work

I have an array data which contains objects which look like that:

{"array":"arr_id_1","direct":"+","axis":"x","s":""}

The axis can be altered to x, y, z. Depending on axis i need to write the value of s into the corresponding array sum_x, sum_y or sum_z. At the end I need the sum of each array.

I wrote the following code using the for-loop to iterate through data , choose the s value and write it into on of the sum-arrays.

function sum_axis(){
var sum_x = [];
var sum_y = [];
var sum_z = [];
for (var i=0 ; i<data.length; i++){
    if (data[i]['axis'] == 'x') {sum_x.splice(i, 1, data[i]['s'])};
    if (data[i]['axis'] == 'y') {sum_y.splice(i, 1, data[i]['s'])};
    if (data[i]['axis'] == 'z') {sum_z.splice(i, 1, data[i]['s'])};
    console.log(data)
    console.log(sum_x, sum_y, sum_z)
    }
}

The problem is that the values are all being written into sum_x. Everything else seems to work just fine. So the 2nd condition is not being touched (at least it seems like that). I can't figure out why it is not working. I am sure it is something simple but I can't wrap my head around it.

I have tried

    if (data[i]['axis'] == 'x') sum_x.splice(i, 1, data[i]['s'])
    if (data[i]['axis'] == 'y') sum_y.splice(i, 1, data[i]['s'])
    if (data[i]['axis'] == 'z') sum_z.splice(i, 1, data[i]['s'])

    if (data[i]['axis'] == 'x') {sum_x.splice(i, 1, data[i]['s'])}
    else if (data[i]['axis'] == 'y') {sum_y.splice(i, 1, data[i]['s'])}
    else if (data[i]['axis'] == 'z') {sum_z.splice(i, 1, data[i]['s'])}

    if (data[i]['axis'] == 'x') sum_x.splice(i, 1, data[i]['s']);
    if (data[i]['axis'] == 'y') sum_y.splice(i, 1, data[i]['s']);
    if (data[i]['axis'] == 'z') sum_z.splice(i, 1, data[i]['s']);

Aucun commentaire:

Enregistrer un commentaire