简体   繁体   中英

How can I access an array value without using array[key]?

I'm writing a simple code to get the value inside an array. I'm using array[key] to get the value stored inside this array, in a for loop.

 var array = ["Foo", "Bar"]; function getValue() { for (var key = 0; key < array.length; key++) { console.log(array[value]); } }

This method is simple and works fine, however, I've read that this could cause security issue ( The Dangers of Square Bracket Notation ), and ESlint is not OK with it, throwing this error:

Generic Object Injection Sink (security/detect-object-injection)

Detects variable[key] as a left- or right-hand assignment operand. ( ESLint reference )

How can I access the value of the array without using this method?

I've already read the related question: Why is it bad pratice calling an array index with a variable? and as this question seems too hard to generalize I decided to ask a new canonical question.

There are a couple of ways to do this.

First : You could use for..of loop. for..of doesnt use the square bracket notation and doesnt give the index directly.

for(let element of list)
{
    console.log(element);
}

Second : The other way is what @Rajesh has mentioned : ForEach.

list.ForEach(element => console.log(element));

Use Array.prototype.at .

['a','b','c','d','e'].at(2); // 'c'

JavaScript offers many method to help you iterate over array for mapping, filtering and only iterating arrays. Look on the few of them:

  1. forEach() method

     let arr = [1,2,3,4,10]; arr.forEach((item, index) => console.log(item)) //1,2,3,4,10 

    This method also allows you to get index of the item.

  2. for-of loop

     for(item of arr) { console.log(item) //1,2,3,4,10 } 

    This new feature introduced in ES6 and this recommended to iterate over arrays.

    If you want manipulate arrays you can use following method, which also iterating over arrays:

  3. filter()

     arr.filter((item, index)=> item > 5) // Return new array [10] 
  4. map()

     arr.map((item, index)=> item*2) // Return new array [2,4,6,8,20] 

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