简体   繁体   中英

variable as array index not working - React

I'm having a problem reaching an array element using a variable as the array index. If I use a number as the array index it works, but the variable does not. The variable has shown to be a number tho.

    ///the array to access:

    const listaProd = [
      {
        name: 'Água..........',
        price: 2.5,
      },
      {
        name: 'Coca-cola.......',
        price: 6,
      },  
      {
        name: 'Almoço executivo..',
        price: 25.5,
      },
    /////etc....
    ];
    ///////////////etc....

/// these are indexes of listaProd to be listed
const ar = [1, 2];


    {
                          ///ar is set as the array: [1, 2] here.
                          /// this means I wanna get listaProd[1] and listaProd[2]

                          ar.map((p, c) => {
                            console.log('-', p);
                            {
                              /**p is a number, either 1 or 2, checked */
                            }
                            let index = parseInt(p);
                            {
                              /**to be sure it is a number... */
                            }
    
                            return (
                              <div className="pedido_client" key={c}>

                                {/**-----it does work! --------*/}
                                {listaProd[1].name}
    
                                {/**does not work */}
                                {listaProd[p].name}
    
                                {/**does not work */}
                                {listaProd[index].name}
    
                                {/**does not work */}
                                {listaProd.at(index).name}

                              </div>
                            );
                          })
                        }

I'm getting the error:

Error in /~/src/App.js (144:1) listaProd[p] is undefined

So, zero is working in the first case as an index, but either 'p' or 'index' are not working as an index. Why?

the whole thing is here for now: (please able the blocked cookies to work) https://stackblitz.com/edit/react-xek249?file=src%2FApp.js,src%2Fstyle.css

you can fork it and test it.

You are mapping this array const ar = [1, 2];

ar.map((value,index)=>console.log(value)) // it will return 1 , 2

And in your array you have index 1 but index 2 is undefined.

{ ar.map((p, c) => {
                    let index = parseInt(p);
                    return (
                      <div className="pedido_client" key={c}>
                        {listaProd[index% ar.length].name }
                      </div>
                    );
                  })

}

{listaProd[index% ar.length].name } allow you to stay within the range of array indexes. Suggestion

  • your ar array is kind of meaningless here, you can directly map this array listaProd .
  • Or you can use index directly from map method. ar.map((val,index)=><div>{arr[index].name})

As seen in the console, second item in the array is undefined because of 2 comma consecutively (,,). So If you delete second comma , array won't contain undefined which causes the issue.

 const listaProd = [ { name: 'Água..........', price: 2.5, },, { name: 'Coca-cola.......', price: 6, }, { name: 'Almoço executivo..', price: 25.5, },, { name: 'Rodízio.........', price: 50, }, { name: 'Sobremesa.....', price: 12.5, }, ]; console.log(`Second value in the array is: ${listaProd[1]}`);

Sedat Polat answered in a comment, so I cannot flag it as the answer,

But it was an extra comma matter.

Thank You!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM