hi, there
can somebody help to resolve this exercice
Print the number and title for each value in titles
. Make sure that the first in the list is 1
, not 0
.
1. The Philosopher's Stone
2. The Chamber of Secrets
3. The Prisoner of Azkaban
// and so on...
titles = ['The Philosopher\'s Stone', 'The Chamber of Secrets', 'The Prisoner of Azkaban', 'The Goblet of Fire', 'The Order of the Phoenix', 'The Half-Blood Prince', 'The Deathly Hallows'];
for(let key in titles){
console.log(`${key} ${titles[key]}`)
}
0 The Philosopher's Stone
1 The Chamber of Secrets
2 The Prisoner of Azkaban
3 The Goblet of Fire
4 The Order of the Phoenix
Can you provide some more context? For example, do you have to use a for … in loop? Or can you use a simple for loop?
I try all of loop I didn’t the resolved solution
in is used to iterate through the properties of an object:
const book = {
'book': 'The Chamber of Secrets',
'character': 'Harry Potter',
'location': 'Hogwarts'
}
for (let key in book){
console.log(`${key}: ${book[key]}`);
}
use of instead of in to iterate through the values of an array (or any iterable)
for (let value of titles) {
console.log(value);
}
Although if you want numbers related to the index, you may want to use a regular for-loop, as mentioned by @taylorsabbag
const words = ["zero", "one", "two", "three"];
for (let i = 0; i < words.length; i++) {
console.log(`${i}. ${words[i]}`);
}
You may need to include some math if you want numbers that are not exactly the same as the index, but are related to it.
const words = ["two", "four", "six", "eight"];
for (let i = 0; i < words.length; i++) {
console.log(`${(i + 1) * 2} = ${words[i]}`);
}