0

Is there a way to assign values in a JavaScript array in the way I do it in PHP.

For example in PHP I can do that:

$ar = array();
$ar[] = "Some value";
$ar[] = "Another value";

Is that posible to be done with JavaScript? Or if not is there any similar way ?

3 Answers 3

11

The direct translation of your original code is

var ar = [];
ar[ar.length] = "Some value";
ar[ar.length] = "Another value";

However a better looking solution is to use the pretty universal push method:

var ar = [];
ar.push("Some value");
ar.push("Another value");
Sign up to request clarification or add additional context in comments.

Comments

8

As with most languages, JavaScript has an implementation of push to add an item to the end of an array.

var ar = [];
ar.push("Some value");
ar.push("Another value");

Comments

5
var myArray = [];
myArray.push('value1');
myArray.push('value1');

Or

var myArray = [];
myArray[myArray.length] = 'value0';
myArray[myArray.length] = 'value1';
myArray[myArray.length] = 'value2';

Check out this reference document for more about javascript arrays: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

Arrays are treated slightly different in javascript. In PHP, an array like this:

PHP

$myArray = array();
$myArray[1] = 'value';
$myArray[10] = 'value';
echo count($myArray); // output: 2

Javascript:

var myArray = [];
myArray[1] = 'value';
myArray[10] = 'value';


console.log(myArray.length); // output: 11

What's going on here? In PHP, an array is an dynamic container. The indexes needn't be sequential - indeed, there is little difference between an associative array (an array with string indexes instead of numeric ones) and a standard array.

In javascript, the concept of "associative array" does not exists in the array context - these would be object literals instead ({}). The array object in javascript is sequential. If you have an index 10, you must also have the indexes before 10; 9,8,7, etc. Any value in this sequential list that is not explicitly assigned a value will be filled with the value undefined:

From the example above:

console.log(myArray); //[undefined, "value", undefined, undefined, undefined, undefined,` undefined, undefined, undefined, undefined, "value"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.