为了账号安全,请及时绑定邮箱和手机立即绑定

Javascript中的类似数组的对象

Javascript中的类似数组的对象

慕运维8079593 2019-12-26 09:54:45
我想知道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 // prototypefoo.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],但我的猜测是答案就在那儿。任何人有任何想法吗?
查看完整描述

2 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

该对象必须具有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;


查看完整回答
反对 回复 2019-12-26
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

像这样?


function foo() {

  this.push('hello');

}

foo.prototype = [];


var bar = new foo();

console.log(bar.length); // 1

console.log(bar); // ["hello"]


查看完整回答
反对 回复 2019-12-26
  • 2 回答
  • 0 关注
  • 638 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信