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';
asked Jan 5, 2017 at 6:06
bijiDango
1,6163 gold badges17 silver badges30 bronze badges
-
not sure what your question is?Yang Yu– Yang Yu2017年01月05日 06:09:56 +00:00Commented Jan 5, 2017 at 6:09
1 Answer 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
answered Jan 5, 2017 at 6:07
Pranav C Balan
115k25 gold badges173 silver badges195 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Rajesh Dixit
I guess you should also include why as well.
bijiDango
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.Pranav C Balan
@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/…
default