How to use array with empty slots in JavaScript

2 Answers

0 votes
const arr = ["c", "javascript", "python"];

arr[5] = "c++";

arr.forEach((item, index) => {
    console.log(`${index}: ${item}`);
});
 
arr.reverse();

console.log();
arr.forEach((item, index) => {
    console.log(`${index}: ${item}`);
});


  
/*
run:
  
0: c
1: javascript
2: python
5: c++

0: c++
3: python
4: javascript
5: c

  
*/

 



answered Apr 30, 2024 by avibootz
0 votes
const arr = ["c", "javascript", "python"];

arr[5] = "c++";

const iterator = arr.keys();

for (const key of iterator) {
    console.log(`${key}: ${arr[key]}`);
}

  
/*
run:
  
0: c
1: javascript
2: python
3: undefined
4: undefined
5: c++

*/

 



answered Apr 30, 2024 by avibootz
...