• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 193
  • Last Modified:

How to get element at particular position from javascript array ?

I have a array in javascript
var cars=["BMW","Mercedes","Audi"];

Open in new window

i want to get the element at particular position from this array.
Is there any function to achieve this ?
i want something which behaves like ArrayList.get() function in java.
arraylist_name.get(2);

Open in new window

Off-course I can't use cars[0],cars[1].... etc.
0
Pradip Shenolkar
Asked:
Pradip Shenolkar
  • 3
  • 2
1 Solution
 
RobOwner (Aidellio)Commented:
var cars=["BMW","Mercedes","Audi"];

console.log(cars[0]); // outputs "BMW"
console.log(cars[1]); // outputs "Mercedes"
console.log(cars[2]); // outputs "Audi"

my article touches on some of this stuff: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_13138-Javascript-is-just-an-Object.html
0
 
Pradip ShenolkarAuthor Commented:
My requirements are such that I can't use cars[0], cars[1] etc
Is there any inbuilt function to do so ?
0
 
RobOwner (Aidellio)Commented:
Nope... that is how you access arrays in javascript, what makes you think otherwise?  What are you trying to do that makes you have to try and access an array like this?
0
 
RobOwner (Aidellio)Commented:
you could do something like this and create your own function:

var cars=["BMW","Mercedes","Audi"];

function getCarAtIndex(i) {
  var t = cars.slice(i,i+1);
  return t[0];
}

console.log(getCarAtIndex(0)); // "BMW"
console.log(getCarAtIndex(1)); // "Mercedes"
console.log(getCarAtIndex(2)); // "Audi"

Open in new window

0
 
Pradip ShenolkarAuthor Commented:
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now