1
2
3
4
5
6
7
8
9
10
11
|
//如題,通常做法就是循環數組,最后在添加length屬性,如:
var obj = {};
var pushArr = [11,22,33,44,55,66];
for(var i=0;i<pushArr.length;i++) {
obj[i] = pushArr[i];
}
obj.length = pushArr.length;
console.log(obj); //{0:11,1:22,2:33,3:44,4:55,5:66,length:6}
|
簡單方法:
1
2
3
4
5
6
7
8
|
//js將數組元素添加到對象中(或 數組轉換成對象)有個小技巧:
var obj = {};
[].push.apply(obj,[11,22,33,44,55,66]);
console.log(obj); //{0:11,1:22,2:33,3:44,4:55,5:66,length:6}
由於obj是個對象沒有像數組的push()方法,所以利用數組的push()以及apply()的特性來將數組作用於pus
|