2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Use Caution When Reinitializing Variables Inside a Loop
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Use Caution When Reinitializing Variables Inside a Loop
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Problem Explanation
|
2018-10-12 15:37:13 -04:00
|
|
|
- This challenge must be solved by redefining the scope of `row[]`.
|
|
|
|
- Below is an example of the desired matrix.
|
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
[[0][0], [0][0], [0][0]];
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
|
|
|
- However the current matrix - seen below - is far from the desired matrix
|
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
[[0][0][0][0][0][0], [0][0][0][0][0][0], [0][0][0][0][0][0]];
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
|
|
|
- This error occurs due to the `row[]` array being declared as a global variable outside of the nested for loop.
|
|
|
|
- However, to fill the matrix correctly the `row[]` array must be reset after each iteration of the outer loop.
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
|
|
|
function zeroArray(m, n) {
|
|
|
|
let newArray = [];
|
|
|
|
for (let i = 0; i < m; i++) {
|
2019-07-24 00:59:27 -07:00
|
|
|
let row = []; /* <----- row has been declared inside the outer loop.
|
2018-10-12 15:37:13 -04:00
|
|
|
Now a new row will be initialised during each iteration of the outer loop allowing
|
|
|
|
for the desired matrix. */
|
|
|
|
for (let j = 0; j < n; j++) {
|
|
|
|
row.push(0);
|
|
|
|
}
|
|
|
|
newArray.push(row);
|
|
|
|
}
|
|
|
|
return newArray;
|
|
|
|
}
|
|
|
|
let matrix = zeroArray(3, 2);
|
|
|
|
console.log(matrix);
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
</details>
|