亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 714 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號