Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array

Tags:

javascript

I usually script/program using python but have recently begun programming with JavaScript and have run into some problems while working with arrays.

In python, when I create an array and use for x in y I get this:

myarray = [5,4,3,2,1]
for x in myarray:
    print x

and I get the expected output of:

5
4
3
..n

But my problem is that when using Javascript I get a different and completely unexpected (to me) result:

var world = [5,4,3,2,1]
for (var num in world) {
    alert(num);
}

and I get the result:

0
1
2
..n

How can I get JavaScript to output num as the value in the array like python and why is this happening?

like image 777
Codahk Avatar asked Jun 13 '11 12:06

Codahk


People also ask

What is an array in JavaScript?

In JavaScript, the array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.

What is JavaScript array with example?

An array is an object that can store multiple values at once. For example, const words = ['hello', 'world', 'welcome']; Here, words is an array.

How do you create an array in JavaScript?

Creating an ArrayUsing an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

What is array list in JavaScript?

In JavaScript, an array is a data structure that contains list of elements which store multiple values in a single variable. The strength of JavaScript arrays lies in the array methods.


2 Answers

JavaScript and Python are different, and you do things in different ways between them.

In JavaScript, you really should (almost) always iterate over an array with a numeric index:

for (var i = 0; i < array.length; ++i)
  alert(array[i]);

The "for ... in" construct in JavaScript gives you the keys of the object, not the values. It's tricky to use on an array because it operates on the array as an object, treating it no differently than any other sort of object. Thus, if the array object has additional properties — which is completely "legal" and not uncommon — your loop will pick those up in addition to the indexes of the "normal" array contents.

like image 71
Pointy Avatar answered Oct 18 '22 06:10

Pointy


The variable num contains the array item's index, not the value. So you'd want:

alert(world[num])

to retrieve the value

like image 36
Tak Avatar answered Oct 18 '22 06:10

Tak