Click here to Skip to main content
15,561,685 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to store the values that correspond to Sunday and Saturday in the table arr2 and display it in the console, the variable a is the number of days in the current month, I calculated it before, when I display the whole table console.log(arr2 ), it displays the values correctly, but when I try to display a specific value eg console.log(arr2[1]) it shows an undefined message in the console.

What I have tried:

<pre lang="Javascript">let arr2 = []; //catch index of samedi's and dimanche's
  let j=0;//initialize index of arr2

const renderDay = () => {
         let td = [];
         for (let i = 1; i <= a; i++) {
          if(days[i].toLocaleDateString("fr-FR", options).slice(0,3)==='sam' ||
          days[i].toLocaleDateString("fr-FR", options).slice(0,3)==='dim'){
             td.push(<td className="test" key={i}>{days[i].toLocaleDateString("fr-FR", options).slice(0,3)}</td>);
             td.push(<td key={i}>{days[i].toLocaleDateString("fr-FR", options).slice(0,3)}</td>);
      return td;

the output of console.log(arr2) is an array contains
0: 6
1: 7
2: 13
3: 14
4: 20
5: 21
6: 27
7: 28

index of sunday's and saturday's of the current month and that's is what I want, but the problem is when I try to console log just specific value example : (arr2[2]) it shows in console undefined
Updated 12-Nov-21 7:07am
Richard MacCutchan 4-Nov-21 13:31pm    
You never store any items in arr2.
Yassine El Aissati 4-Nov-21 13:37pm    
I store items in arr2 in renderDay function ,when I use console.log(arr2) it shows me all the correct values who i wanted in the console,but i can't access to every specific value , when i type console.log(arr2[1]) it shows undefined in the console
Richard MacCutchan 4-Nov-21 13:43pm    
You have two separate blocks of code so it is difficult to see which comes where.
Richard Deeming 4-Nov-21 13:38pm    
You can replace arr2[j] = i; j++; with arr2.push(i);, which will do the same thing.

1 solution

// This is an empty Array without any objects/ values in it.
let arr2 = [];

console.log(arr2); // []
console.log(arr2[0]); // undefined

// Solution1: pushing the value to the array one by one

console.log(arr2); // [ 1 ]
console.log(arr2[0]); // 1

// Solution2: Mapping default values to the array of size 4
let arr3 = [...Array(4)].map(x => 0);

3xh89vqvr - JavaScript - OneCompiler[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900