Javascript中的类似数组的对象

我想知道jQuery如何构造其类似数组的对象。我要尝试解决的关键问题是如何设法使控制台将其解释为数组并以此形式显示。我知道它与length属性有关,但是在玩了一点之后我还是不太清楚。


我知道这比普通的数组(如下面的示例)没有技术优势。但是我认为这是用户进行测试和调试时的重要语义元素。


像对象一样的普通数组。


function foo(){

    // Array like objects have a length property and it's properties use integer

    // based sequential key names, e.g. 0,1,2,3,4,5,6 just like an array.

    this.length = 1;

    this[0] = 'hello'

}

// Just to make sure add the length property to the prototype to match the Array 

// prototype

foo.prototype.length = 0;


// Give the Array like object an Array method to test that it works     

foo.prototype.push = Array.prototype.push


// Create an Array like object 

var bar = new foo;


//test it 

bar.push('world');


console.log(bar);

// outputs 

{ 0: 'hello',

  1: 'world',

  length: 2,

  __proto__: foo

}

jQuery输出的位置


var jQArray = $('div')


console.log(jQArray);


// outputs

[<div></div>,<div></div>,<div></div>,<div></div>]

如果你跑


console.dir(jQArray)


// Outputs


{ 0: HTMLDivElement,

  1: HTMLDivElement,

  2: HTMLDivElement,

  3: HTMLDivElement,

  4: HTMLDivElement,

  context: HTMLDocument,

  length: 5,

  __proto__: Object[0]

 }

jQuery对象的原型特别有趣,因为它是Object而不是预期的jQuery.fn.init,而且[0]表示某些东西,因为这是您在获取时得到的。


console.dir([])

// outputs Array[0] as the object name or Array[x] x being the internal length of the

// Array

我不知道jQuery如何将它的原型设置为Object [0],但我的猜测是答案就在那儿。任何人有任何想法吗?


慕运维8079593
浏览 640回答 2
2回答

慕桂英3389331

该对象必须具有length和splice> var x = {length:2, '0':'foo', '1':'bar', splice:function(){}}> console.log(x);['foo', 'bar']和FYI,Object[0]作为原型的原因完全相同。浏览器将原型本身视为数组,因为:$.prototype.length == 0;$.prototype.splice == [].splice;

泛舟湖上清波郎朗

像这样?function foo() {&nbsp; this.push('hello');}foo.prototype = [];var bar = new foo();console.log(bar.length); // 1console.log(bar); // ["hello"]
打开App,查看更多内容
随时随地看视频慕课网APP