bijiDango
bijiDango

Reputation: 1596

How to declare Javascript array with numeric keys (like php does)?

What I do in php:

$arr = [1=>'a', 3=>'b', 2017=>'zzzzZZZZ'];

What I konw in js:

var arr = [];
arr[1] = 'a';
arr[3] = 'b';
arr[2017] = 'zzzzZZZZ';

Upvotes: 2

Views: 264

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115242

Your code would make an array of length 2018 since the largest array index defined is 2017 and the remaining undefined elements are treated as undefined.

var arr = [];
arr[1] = 'a';
arr[3] = 'b';
arr[2017] = 'zzzzZZZZ';

console.log(arr.length, arr);


In JavaScript, there is no associative array instead there is object for key-value pair of data.

var obj = {
    1 : 'a',
    3 : 'b',
    2017 : 'zzzzZZZZ'
}

var obj = {
  1: 'a',
  3: 'b',
  2017: 'zzzzZZZZ'
}

console.log(obj);

Refer : javascript Associate array

Upvotes: 1

Related Questions