I'm using a javascript library which returns arrays not starting from zero like starting from 26 or 1500, what i want to do is a method to get the first element in that array regardless of the index number starting with 0 or any other number.
Are they any method to do this in javascript ?
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
In computer science, array indices usually start at 0 in modern programming languages, so computer programmers might use zeroth in situations where others might use first, and so forth.
In array, the index tells the distance from the starting element. So, the first element is at 0 distance from the starting element. So, that's why array start from 0.
Can we change the starting index of an array from 0 to 1 in any way? Explanation: No. You can not change the C Basic rules of Zero Starting Index of an Array.
I suggest to use Array#some
. You get the first nonsparse element and the index. The iteration stops immediately if you return true
in the callback:
var a = [, , 22, 33],
value,
index;
a.some(function (v, i) {
value = v;
index = i;
return true;
});
console.log(index, value);
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