简体   繁体   English

如何遍历javascript数组并调用更新同一数组的函数?

[英]How can I iterate through a javascript array and call a function that updates the same array?

I have this array: 我有这个数组:

var test.qs =
[
 {"answer":null,
  "testQuestionId":710
  "synchronized":true},
 {"answer":null,
  "testQuestionId":711
  "synchronized":false
]

I would like to call a function on all the array objects that have the syncronized property equal to false like this: 我想在所有具有syncronized属性等于false的数组对象上调用一个函数,如下所示:

if (!test.qs[x].synchronized) {
    httpPutTestQuestion(number)
    .success(function (data) {
        test.qs[x].synchronized = true;
    })
}

But how can I do this as if I put this into a for loop then when the function returns I won't still have the value x? 但是我该怎么办,就好像我将其放入for循环中一样,那么当函数返回时,我将仍然没有值x?

I think this should work for you. 我认为这应该为您工作。

test.qs.forEach(function (q) {
if (!q.synchronized) {
    httpPutTestQuestion(number)
    .success(function (data) {
        q.synchronized = true;
    })
}
})

Why don't you use the plain old loop, like this 为什么不使用普通的旧循环,像这样

var i;
for (i = 0; i < qs.length; i += 1) {
    if (qs[i].synchronized === false) {
        httpPutTestQuestion(number)
            .success(function (data) {
                test.qs[x].synchronized = true;
            })
        };
    }
}

You can get the length of the array with the length property. 您可以使用length属性获取数组的length Also note that, the variable names inJavaScript cannot have . 另请注意,JavaScript中的变量名称不能具有. in them. 在他们中。 So, 所以,

var test.qs = ....

will fail. 将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM