【原创】数组的key为非数字时

正常情况下,数组的默认key为数组,如:

var arr=["ta","tt","te"];console.log(arr[1]);
"tt"

当key为非直接数字时,两种情况,一种为数字形式字符串,一种为非数字形式字符串:

①、数字形式字符串:数字形式字符串,默认将字符串转化为对应的数字下标,其他为定义项为undefined

var arr=[];arr["2"]="team2";arr[4]="team4";console.log(arr);
[2: "team2", 4: "team4"] 



var arr=[];arr["2"]="team2";arr[4]="team4";
console.log(arr.length);
5 


var arr=[];arr["2"]="team2";arr[4]="team4";
for(var key in arr){console.log(arr[key])};
team2 
team4 


var arr=[];arr["2"]="team2";arr[4]="team4";console.log(arr[0]);

undefined 

②、当为非数字形式字符串时,这时候,实际arr已经不是一个数组,而是一个json对象{key1:"team1",key2:"team2"} 这个json对象的默认length为0(默认属性)

var arr=[];arr["key1"]="team1";arr["key4"]="team4";
console.log(arr.length);

0 

var arr=[];arr["key1"]="team1";arr["key4"]="team4";
console.log(arr);

[key1: "team1", key4: "team4"] 


var arr=[];arr["key1"]="team1";arr["key4"]="team4";
console.log(arr[0]);

undefined 


var arr=[];arr["key1"]="team1";arr["key4"]="team4";
console.log(arr[key1]);

ReferenceError: key1 is not defined

var arr=[];arr["key1"]="team1";arr["key4"]="team4";
console.log(arr["key1"]);

team1 

var arr=[];arr["key1"]="team1";arr["key4"]="team4";
console.log(arr.key1);

team1 

 

所以,如果定义var arr=[];arr["999"]="girl",系统默认将“999”转化成999,则数组length为1000,前面的999个数组元素占用系统内存,如果需要不占用系统内存

可以写成json形式,如:

var arr=[];arr["_"+999]="girl";console.log(arr);
[_999: "girl"] 

 实际获取可以写成:

var arr=[];arr["_"+999]="girl";console.log(arr["_"+999]);
girl 

 

posted on 2016-05-27 11:54  东渐  阅读(187)  评论(0编辑  收藏  举报

导航