我想知道jQuery如何構(gòu)造其類似數(shù)組的對象。我要嘗試解決的關(guān)鍵問題是如何設(shè)法使控制臺將其解釋為數(shù)組并以此形式顯示。我知道它與length屬性有關(guān),但是在玩了一點之后我還是不太清楚。我知道這比普通的數(shù)組(如下面的示例)沒有技術(shù)優(yōu)勢。但是我認為這是用戶進行測試和調(diào)試時的重要語義元素。像對象一樣的普通數(shù)組。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而不是預(yù)期的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如何將它的原型設(shè)置為Object [0],但我的猜測是答案就在那兒。任何人有任何想法嗎?
Javascript中的類似數(shù)組的對象
慕運維8079593
2019-12-26 09:54:45