如何迭代javascript数组并调用更新相同数组的函数?

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

本文关键字:数组 更新 函数 调用 迭代 javascript 何迭代      更新时间:2023-09-26

我有这样一个数组:

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

我想对所有同步属性为false的数组对象调用一个函数,如下所示:

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

但是我怎么能做到这一点,如果我把它放到for循环中,那么当函数返回时,我仍然不会有值x?

我想这应该适合你。

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

为什么不使用普通的循环呢,像这样

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;
            })
        };
    }
}

可以通过length属性获得数组的长度。还要注意,javascript的变量名中不能有.

var test.qs = ....

将会失败。