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';
1
  • not sure what your question is? Commented Jan 5, 2017 at 6:09

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I guess you should also include why as well.
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 : that's because the property name starts with a name so you can't use dot notation ...... check the docs : developer.mozilla.org/en/docs/Web/JavaScript/Reference/…

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.