我试图替换JSON格式的变量中的值。
这是我的数据格式:
{
"y":-10.9569,
"x":26.4007,
"z":11.9888,
"t":109.122
},
{
"y":-9.78734,
"x":6.85818,
"z":11.9832,
"t":109.439
},
{
"y":-9.30135,
"x":-2.72265,
"z":11.9493,
"t":109.594
},
{
"y":-7.90726,
"x":-33.3971,
"z":12.012,
"t":110.14
},
{
"y":-6.8483,
"x":-56.5212,
"z":11.916,
"t":110.611
},
我尝试了这段代码,但它输出的值保持不变:
for(var i = 1; i < json.length; i++ ) {
json.recording.path[i].t = json.recording.path[i].t*0.9;
}
console.log(json);
但是,当我省略for
循环时,代码正确地替换了值:
json.recording.path[1].t = json.recording.path[1].t*0.9;
console.log(json);
这里有什么问题?
虽然提供的json数据不完整,但根据您提供的数据应该是完整的
for(var i = 1; i <json.recording.path.length; i ++){...
你正在迭代变量“json”的长度,但修改'json.recording.path“。你也是从索引1而不是0开始,这将导致它跳过第一个元素。
试试这个:
for(var i = 0; i < json.recording.path.length; i++ ) {
(正如一些人在评论中指出的那样,这不是JSON,它是一个javascript对象.JSON是一种用于传输和存储对象的字符串格式。)
使用for循环,您可以遍历json元素并进行计算。
var json = [{
"y":-10.9569,
"x":26.4007,
"z":11.9888,
"t":109.122
},
{
"y":-9.78734,
"x":6.85818,
"z":11.9832,
"t":109.439
},
{
"y":-9.30135,
"x":-2.72265,
"z":11.9493,
"t":109.594
},
{
"y":-7.90726,
"x":-33.3971,
"z":12.012,
"t":110.14
},
{
"y":-6.8483,
"x":-56.5212,
"z":11.916,
"t":110.611
}];
for(var i=0;i<json.length;i++){
json[i].t = json[i].t * 0.9;
console.log(json[i].t);
}