类数组

关于类数组

在网上搜索了很多,都没有关于类数组的介绍和使用,这下只能靠自己胡编乱造了。aa3901412af3e196f9e30e058b7f7cfc.jpg

一个标准的类数组

var arr = {
0 : 'test',	
1 : 18,

2 : 'male',

name : '墨小白',

length : 2,

push : Array.prototype.push,

splice : Array.prototype.slice

}

length 为必须属性,第0位算不算到length上很重要,最好写入  push  ,

splice  一旦写入,这个类数组输出的时候就和数组长的一样。

优点是存储数据更强大,可以拿来当数组使用,也可以使用对象的属性。

控制台测试:

QQ浏览器截图_20180314095455_2D8D29C85A154d36ADEEF31814BBF22B.jpg


练习题:

求  arr  输出是什么。

var arr = {
	
1 : 18,

2 : 'male',

length : 2,

push : Array.prototype.push,

splice : Array.prototype.slice
}
	
arr.push('c');

arr.push('d');

典型错误答案:

arr[18,male,'c','d']

解析:

首先要知道 push 的内部原理再来做这道题

Array.prototype.push = function (a) {
	
this[this.length] = a;

this.length ++;

}

此时的  arr.push  运行过程即是

Array.prototype.push = function ('c') {
	
this[2] = 'c';

this.length ++;

}

所以会覆盖第二位

QQ浏览器截图_20180314094519_F616F24630AE49118AC0BF94F847AF0B.jpg

猜你喜欢

转载自blog.csdn.net/dfggffdd/article/details/80108424
今日推荐