I solved Challenge 16 with no problem. I also found an answer for Challenge 17 but I don't understand why I can only use square brackets for adding property into an object like this: loopNumbers[nestedArr[i][0]] = nestedArr[i][1]
So, my questions are:
- Why can't I use dot notation like this?:
loopNumbers.nestedArr[i][0] = nestedArr[i][1]
If I use dot notation, then it saysType Error on line 120: Cannot read property '0' of undefined
- How come I don't need to put semicolon after the line of code
loopNumbers[nestedArr[i][0]] = nestedArr[i][1]
?
Below are the challenges.
Challenge 16
You are provided with an empty array called
nestedArr
. Using a for loop, add 5 sub-arrays tonestedArr
, with each nested array containing the string 'loop' concatenated with the corresponding index innestedArr
as it's first element, and just the index as it's second element. Example of a subarray -['loop3', 3]
My answer:
let nestedArr = [];
for(let i=0; i<5; i++){
nestedArr.push(['loop'+i, i]);
}
console.log(nestedArr);
Challenge 17
Create a variable called
loopNumbers
and initialize it to an empty object literal. Using a for loop, iterate throughnestedArr
from the previous challenge. For each iteration of your loop, assign a new property toloopNumbers
where the property name is the first element in each nested array innestedArr
and the value is the second element.
My answer:
let loopNumbers = {};
for (let i = 0; i < nestedArr.length; i++) {
loopNumbers[nestedArr[i][0]] = nestedArr[i][1]
}
console.log(loopNumbers);