数组像Javascript中的对象

Ash*_*kes 31 javascript arrays jquery javascript-objects

我想知道jQuery如何构造其类似数组的对象.我正在尝试解决的关键是它如何设法让控制台将其解释为数组并将其显示为这样.我知道它与长度属性有关,但在玩了一下后我无法弄明白.

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

像Object这样的普通数组.

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
}
Run Code Online (Sandbox Code Playgroud)

jQuery的输出位置

var jQArray = $('div')

console.log(jQArray);

// outputs
[<div></div>,<div></div>,<div></div>,<div></div>]
Run Code Online (Sandbox Code Playgroud)

如果你跑

console.dir(jQArray)

// Outputs

{ 0: HTMLDivElement,
  1: HTMLDivElement,
  2: HTMLDivElement,
  3: HTMLDivElement,
  4: HTMLDivElement,
  context: HTMLDocument,
  length: 5,
  __proto__: Object[0]
 }
Run Code Online (Sandbox Code Playgroud)

jQuery对象的proto特别有趣,因为它的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
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ahn 43

对象必须有lengthsplice

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

和FYI Object[0]一样,原型也是出于同样的原因.浏览器将原型本身视为一个数组,因为:

$.prototype.length == 0;
$.prototype.splice == [].splice;
Run Code Online (Sandbox Code Playgroud)

  • 我知道它会那么简单,谢谢. (2认同)