admin管理员组

文章数量:1297011

I was just thinking back to the good old days when I used to use VBScript (good old days?!?!? What am I thinking?), and I remember using two very useful methods with arrays, these were UBound and LBound. Now I don't think JavaScript has these and if I wanted to make my own I could extend the object however, I just tried doing this to return the upperbound item (or the last item of the array)

var myArray = ['1','2','3','4','5','6','seven', 8, 'nine','10'];
document.write(myArray.length + ' ' + myArray[myArray.length]);

the myArray.length returns what it should however when I try and output the last item using myArray[myArray.length] I get undefined? Anyone know why this is?

Thanks

I was just thinking back to the good old days when I used to use VBScript (good old days?!?!? What am I thinking?), and I remember using two very useful methods with arrays, these were UBound and LBound. Now I don't think JavaScript has these and if I wanted to make my own I could extend the object however, I just tried doing this to return the upperbound item (or the last item of the array)

var myArray = ['1','2','3','4','5','6','seven', 8, 'nine','10'];
document.write(myArray.length + ' ' + myArray[myArray.length]);

the myArray.length returns what it should however when I try and output the last item using myArray[myArray.length] I get undefined? Anyone know why this is?

Thanks

Share Improve this question edited Jun 18, 2014 at 13:49 Zong 6,2305 gold badges33 silver badges46 bronze badges asked Oct 15, 2011 at 11:10 Mark SandmanMark Sandman 3,33312 gold badges42 silver badges61 bronze badges 2
  • Javascript array starts with 0 – Rosdi Kasim Commented Oct 15, 2011 at 11:14
  • And don't forget that there can also be undefined elements in the middle of the array. – nnnnnn Commented Oct 15, 2011 at 12:18
Add a ment  | 

2 Answers 2

Reset to default 6

The last element of myArray is at myArray.length - 1, since arrays in Javascript are 0-indexed. So , myArray[myArray.length -1] is what you're looking for.

The indexes start at 0. The last element is at myArray.length - 1

本文标签: javascriptUndefined when trying to get the upper bound of arrayStack Overflow