jQuery 是如何使其类数组集合对象在浏览器控制台中像数组一样显示的?

问题描述 投票:0回答:2

我想知道 jQuery 如何构造其类似数组的对象。我想要解决的关键问题是它如何设法让控制台将其解释为数组并按此方式显示。我知道这与长度属性有关,但玩了一下后我不太明白。

我知道这与普通的类似数组的对象相比没有技术优势,如下例所示。但我认为当用户测试和调试时这是一个重要的语义元素。

像对象一样的普通数组。

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],但我的猜测是答案就在那里。有人有什么想法吗?

javascript jquery arrays javascript-objects
2个回答
43
投票

该对象必须具有

length
splice

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

仅供参考,将

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

$.prototype.length == 0;
$.prototype.splice == [].splice;

-1
投票

像这样吗?

function foo() {
  this.push('hello');
}
foo.prototype = [];

var bar = new foo();
console.log(bar.length); // 1
console.log(bar); // ["hello"]
© www.soinside.com 2019 - 2024. All rights reserved.