Javascript 中的类数组对象 [英] Array Like Objects in Javascript

查看:43
本文介绍了Javascript 中的类数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 jQuery 如何构造它的类数组对象.我正在努力解决的关键问题是它如何设法让控制台将其解释为数组并将其显示为数组.我知道这与 length 属性有关,但玩了一会儿后我不太明白.

I'm wondering how jQuery constructs its array-like object. The key thing I'm trying to work out is how it manages to get the console to interpret it as an array and display it as such. I know it has something to do with the length property, but after playing a bit I can't quite figure it out.

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

I know this has no technical advantage over a normal array like object as in the example below. But I think it's an important semantic element when users are testing and debugging.

一个普通的数组,如对象.

A normal Array like 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
}

jQuery 将输出的位置

Where as jQuery would output

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 对象的 proto 尤其有趣,因为它是对象而不是预期的 jQuery.fn.init,而且 [0] 表示某些东西,因为这就是你得到的.

The proto of the jQuery object is especially interesting since its the Object and not jQuery.fn.init as would be expected, also the [0] indicates something as this is what you get when you.

console.dir([])
// outputs Array[0] as the object name or Array[x] x being the internal length of the
// Array

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

I have no idea how jQuery has set it's proto to be Object[0] but my guess is that answer lies somewhere in there. Anyone got any ideas?

推荐答案

对象必须有lengthsplice

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

<小时>

仅供参考,Object[0] 作为原型的原因完全相同.浏览器将原型本身视为一个数组,因为:


and FYI, the Object[0] as the prototype is for exactly the same reason. The browser is seeing the prototype itself as an array because:

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

这篇关于Javascript 中的类数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆