简体   繁体   中英

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:

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?

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. Also note that, the variable names inJavaScript cannot have . in them. So,

var test.qs = ....

will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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