how does jquery return an array of the selected elements

孤人 提交于 2019-12-05 21:41:05

To work "as an array" (we usually speak of "array-like" object) you don't inherit from Array, you simply have to

  • have a relevant property named length
  • have properties "0", "1"... length-1 (you might skip some)

Example :

var a = {
  length: 2,
  "0": 'first',
  "1": 'second'
}
var b = [].slice.call(a); // yes, Array functions work !
console.log(b); // logs ["first", "second"] 

Of course you can make all this easier for the lib users by defining a prototype based class and the relevant prototype functions (just as jQuery does) :

var A = function(){
  this.length = 2;
  this['0'] = 'first';
  this['1'] = 'second';
}
A.prototype.slice = [].slice;
A.prototype.splice = [].splice;
var a = new A, b = a.slice();
console.log(a); // logs ["first", "second"] because of the splice function
console.log(Array.isArray(a));
console.log(b); // logs ["first", "second"] because it's really an array
console.log(Array.isArray(b)); // true

If you want your objects to be logged as arrays, you need to have the splice function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!