Nested for loops and multidimensional arrays

I am trying to understand how nested loops work with multidimensional arrays in JavaScipt, and I am a bit stuck at one point. Using stock example

var arr = [[1,2], [3,4], [5,6]];
for (var i=0; i < arr.length; i++) {
    for (var j=0; j < arr[i].length; j++) {
        console.log(arr[i][j]);
    }
}

This outputs 1 2 3 4 5 6, as I expected. However, if I add numbers to the end of the external array:

var arr = [[1,2], [3,4], [5,6], 7, 8];
for (var i=0; i < arr.length; i++) {
    for (var j=0; j < arr[i].length; j++) {
        console.log(arr[i][j]);
    }
}

Am I still getting the same result 1 2 3 4 5 6 ?? I am confused why 7 and 8 are not caught in a loop. Interestingly, if I use strings instead:

var arr = [["a","b"], ["c","d"], "y", "z"];
for (var i=0; i < arr.length; i++) {
    for (var j=0; j < arr[i].length; j++) {
        console.log(arr[i][j]);
    }
}

The conclusion is bcdyz, as I expected. Why does it behave differently for strings?

+4
source share
5 answers

This is how things look in modern Javascript.

"" "". Iterable - , ... iterate - for..of.

for (let item of someIterableThing)
    // use item

( for - for(var i...i < length) - , length .)

, for...of , .

, . ,

[ [1,2], [3,4], "foobar" ]

, .

[ [1,2], [3,4], 999]

, .

, , :

 let isIterable = x => x && x[Symbol.iterator]

(. ).

:

for (let item of array)
    if (isIterable(item))
        for (let subItem of item)
            console.log(subItem)
    else
        console.log(item)

Javascript . , , 5 , . , , , , for.

( , for , :

text, , . A -:

for (var i = 0; i < text.length; i++)  
     do_something_with(text[i]) // ;(

B -:

for (let str of text)  
     do_something_with(str) // :)

text . , . 100 , :

  for (var file = TextFile; !file.eof(); file.getNext())
      do_something_with(file.currentLine)

, .

B .)

0

, , (- ). , , . ( , , .) 7 8 , arr[i].length undefined , " " length. "y" length of 1, , "" "y", "y".

for , Array.forEach(), , .

var arr = [[1,2], [3,4], [5,6], 7, 8];
var output = "";

// Enumerate the top-level array:
arr.forEach(function(value){
  // Check to see if the item is an array
  if(value instanceof Array){
    // If so, enuerate that nested array
    value.forEach(function(nestedValue){
      // Add the nested array value to the output
      output += nestedValue + " " ;
    });
  } else {
    // Item is not an array, just add its value to the output
    output += value + " ";
  }
});

console.log(output);
Hide result

, , , , , , , FYI, - :

console.log([[1,2], [3,4], [5,6], 7, 8].toString().split(",").join(" "));
Hide result
+2

String, Array, TypedArray, Map Set , @@iterator. Number :

const iterate = v => {
  for (var i = 0; i < v.length; i++) console.log(v[i])
}

iterate([1, 'two', 777]) // iterates by element
iterate('abc') // iterates by symbol
iterate(123) // does not iterate
Hide result
+2

. console.log(arr[i][j]);, arr arr[i].

[j]. 7 8 - , , .

, :

 var arr = [["a","b"], ["c","d"], "y", "z"];
 for (var i=0; i < arr.length; i++) {
   for (var j=0; j < arr[i].length; j++) {
/* 		console.log(arr[i][j]);  */
  }
}

var foo = "a";
var bar = foo[0];

console.log(bar);
Hide result

Strings behave like arrays of characters, so you get a letter that returns itself when you call foo [0], it returns a.

+1
source

Why does it behave differently for strings?

Because strings are treated as an array of characters.

The JavaScript string holds a series of characters, such as "John Doe." Access to each character is possible using the array index, and also has a method lengthfor obtaining the size of the string. Therefore, yours "y", "z"works, but not 7, 8, since they are not an array.

+1
source

Source: https://habr.com/ru/post/1694077/


All Articles