I have a 2D array. I currently access that array using notation such as:
myArray[5][9]
(for example).
What is the safest way to check whether or not a certain array element exists? For example, let's say I am looping through the array and retrieving a property of each array element like so:
myArray[5][9].firstName
I then come to myArray[9][11].firstName
(for example) which doesn't exist. Clearly this will throw an exception as the element doesn't exist.
How can I deal with this? I'm not looping through the entire array (i'm accessing it's contents randomly and say using myArray.length
in a for loop will not work.
Is there a JS function / method for checking whether or not an array element exists?
Thanks.
Safe call operator ?.
looks fine. Warning: many, but not all implementations (and versions) of JavaScript supports it.
For your example it will looks like
myArray[5][9]?.firstName
EDIT: Thanks to Asaf comment there is more safe version
myArray?.[5]?.[9]?.firstName
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With