2

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';
bijiDango
  • 1,385
  • 3
  • 14
  • 28

1 Answers1

1

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

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • I guess you should also include **why** as well. – Rajesh Jan 05 '17 at 06:08
  • Very odd that I can't use `obj.1` to get the value but `obj[1]` or `obj['1']`. Seems that JS object stores data as array, and the most basic way to fetch data is also array. In the meanwhile, array act like restricted object. – bijiDango Jan 05 '17 at 06:31
  • @bijiDango : that's because the property name starts with a name so you can't use dot notation ...... check the docs : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Dot_notation – Pranav C Balan Jan 05 '17 at 06:32