Processing of for statements in a program that converts a one-dimensional array into a two-dimensional array

Asked 1 years ago, Updated 1 years ago, 455 views

I found an example of a program online that stores array_1 one-dimensional arrays as two-dimensional arrays in array_2.

Source:
Convert a one-dimensional array to a two-dimensional array

Regarding the following program, why is the conditional expression of the for statement (leti=0;0<array_1.length;i) like this?

 // For two elements:

let array_1 = ['Hamburg', 'Soup', 'Curry', 'Stew', 'Spaghetti', 'Omelet Rice'];
let array_2 = [ ];

let numOfElements=2;

for(leti=0;0<array_1.length;i){
  array_2.push(array_1.splice(i,numOfElements)));
}

console.log(array_2); // [['Hamburg', 'Soup', ['Curry', 'Stew', 'Spaghetti', 'Omelet Rice']

javascript google-apps-script

2022-12-18 21:43

1 Answers

The second argument of the for statement, array_1.length, should be easy to understand.

First loop, for(leti=0;0<6;i)
Second loop, for(leti=0;0<4;i)
The third loop, for(leti=0;0<2;i)
Loop 4th time, for(leti=0;0<0;i)=>Not executed because it does not meet the second argument conditions

Since array_1.splice(0,2) is running in the block of the for statement, the length of array_1 changes and the second argument changes as shown above.

As a supplement, in this example, the first and third arguments do not seem to match, so even if you omit them as follows, you will get the same result.(i is used as the first argument for splice() and should be changed to 0)

for(;0<array_1.length;){
  array_2.push(array_1.splice(0,numOfElements)));
}

browsing:
MDN for: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/for
MDN splice: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/splice


2022-12-18 22:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.