小编典典

Javascript中的类似数组的对象

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],但我猜答案是在那里。任何人有任何想法吗?


阅读 485

收藏
2020-05-01

共1个答案

小编典典

该对象必须具有lengthsplice

> var x = {length:2, '0':'foo', '1':'bar', splice:function(){}}
> console.log(x);
['foo', 'bar']

和FYI,Object[0]作为原型的原因完全相同。浏览器将原型本身视为数组,因为:

$.prototype.length == 0;
$.prototype.splice == [].splice;
2020-05-01