Can't iterate over my array/object. Javascript

2019-01-20 18:44发布

问题:

This question already has an answer here:

  • Is Chrome's JavaScript console lazy about evaluating arrays? 6 answers

I really don't understand what could be going on here. So I have a function which takes a 2d array and a string and iterates through the 2d array and checks if any subarrays contain the string. But somehow I can't iterate over this object/array and I'm really confused as to what it actually is. I've done lots of iteration in javascript. I've tried for-in, for-of (es6), C stlye(like below), forEach(callback), map... nothing works.

    _makeOrUpdateCase = (arrayOfArrays, str) => {
    console.log(arrayOfArrays); //returns the object/array shown in image below, expected
    console.log(typeof(arrayOfArrays)); //object
    console.log(Array.isArray(arrayOfArrays)); //true - huh? is this array or object??
    for (var i = 0; i < arrayOfArrays.length; i++) {
        console.log(arrayOfArrays[i]) //this does not work
        console.log(i); //nothing is printed out, as if the loop is simply ignored
    }

Here is the output I get.. you can see that the stuff I'm printing in the loop is not executed. I know javascript can be weird but c'mon what is going on here, I have no idea what to google. I've iterated over arrays and objects lots of times in this code.

回答1:

tl;dr: Your loop is fine but the array is empty even if it appears in the console that it is not.

You are logging/accessing the array before it was populated. That's evident from the Array[0] in the output (indicating an array of length 0), even though it appears to have an element. This can happen if you have an asynchronous process, like Ajax, but are logging/accessing the array before the asynchronous process is done.

If you hover over the little i in the console, it will tell you that the value was just evaluated, i.e. it shows the value the variable has at the time you click the triangle, not at the time you log the value in code. By the time you click the triangle, the asynchronous process will likely have finished.

However, if you use console.log(JSON.stringify(arrayOfArrays)); instead you will see that the array is empty.

Here is simple example that demonstrates the issue (open the browser console and expand the array, works in Chrome at least):

// Open the browser console
var arr = [];
console.log(arr);
arr.push(1,2,3);

The only solution is to call _makeOrUpdateCase only after the asynchronous process is done. Since you are not showing how/when/where the function is called, this is all that can be said about the problem.


Related: Is Chrome's JavaScript console lazy about evaluating arrays?