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.
Pradip ShenolkarAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Pradip ShenolkarAuthor Commented:
thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.