I am expecting
"Lesson1"
"Lesson2"
.
.
.
"Lesson10",
but on console it is showing
Uncaught TypeError: Cannot read properties of undefined (reading
‘name’)
at app.js:14:26
let myWork = [];
for(let i = 1; i <= 10; i++){
let stat = i % 2 ? true : false;
let temp ={
name: `Lesson${i}`,
status: stat
}
myWork.push(temp);
document.write(myWork[i].name+"<br>");
}
>Solution :
Its a simple issue, when you push to the array the position starts from 0, but your i starts from 1
See below.
let myWork = [];
for (let i = 0; i <= 10; i++) {
let stat = i % 2 ? true : false;
let temp = {
name: `Lesson${i}`,
status: stat
}
myWork.push(temp);
document.write(myWork[i].name + "<br>");
}
If you want to start from Lesson1 try this
let myWork = [];
for (let i = 1; i <= 10; i++) {
let stat = i % 2 ? true : false;
let temp = {
name: `Lesson${i}`,
status: stat
}
myWork.push(temp);
document.write(myWork[i - 1].name + "<br>");
}