开发者

JavaScript arrays behave like PHP?

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 = ar开发者_如何学Cray();
$ar[] = "Some value";
$ar[] = "Another value";

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


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");


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");


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"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜