我有一个数组data
,其中包含如下所示的对象:
data = [{
"array": "arr_id_0",
"direct": "+",
"axis": "x",
"s": "1"
},
{
"array": "arr_id_1",
"direct": "+",
"axis": "y",
"s": "2"
},
{
"array": "arr_id_2",
"direct": "+",
"axis": "z",
"s": "3"
},
{
"array": "arr_id_3",
"direct": "+",
"axis": "x",
"s": "4"
}
]
axis
可以更改为x
,y
,z
。根据{{1}},我需要将axis
的值写入相应的数组s
,sum_x
或sum_y
。最后,我需要每个数组的总和。
我使用for循环编写了以下代码来迭代sum_z
,选择s值并将其写入data
- 数组。
sum
问题是这些值全部写入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)
}
}
。其他一切似乎都很好。所以第二个条件没有被触及(至少看起来像那样)。我无法弄清楚它为什么不起作用。我确信它很简单,但我无法绕过它。
我试过了
sum_x
预期输出为:
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']);
实际输出是:
sum_x = [1,4]
sum_y = [2]
sum_z = [3]
答案 0 :(得分:2)
您的代码没问题。尝试在你的控制台中运行它
var data = [{"array":"arr_id_0","direct":"+","axis":"x","s":"1"},
{"array":"arr_id_1","direct":"+","axis":"y","s":"2"},
{"array":"arr_id_2","direct":"+","axis":"z","s":"3"},
{"array":"arr_id_3","direct":"+","axis":"x","s":"4"}]
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)
}
}
sum_axis()
&#13;
我没有改变任何事情。您可能访问了错误的数据变量。
答案 1 :(得分:1)
你的代码工作正常,可能是因为你在循环中有最后一个console.log
,如果你把它取出循环然后你会得到你想要的结果。
var data = [{
"array": "arr_id_0",
"direct": "+",
"axis": "x",
"s": "1"
},
{
"array": "arr_id_1",
"direct": "+",
"axis": "y",
"s": "2"
},
{
"array": "arr_id_2",
"direct": "+",
"axis": "z",
"s": "3"
},
{
"array": "arr_id_3",
"direct": "+",
"axis": "x",
"s": "4"
}
];
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); // [ '1', '4' ] [ '2' ] [ '3' ]
}
sum_axis(data);