慕運(yùn)維8079593
2019-12-26 09:54:45
我想知道jQuery如何構(gòu)造其類似數(shù)組的對(duì)象。我要嘗試解決的關(guān)鍵問(wèn)題是如何設(shè)法使控制臺(tái)將其解釋為數(shù)組并以此形式顯示。我知道它與length屬性有關(guān),但是在玩了一點(diǎn)之后我還是不太清楚。我知道這比普通的數(shù)組(如下面的示例)沒(méi)有技術(shù)優(yōu)勢(shì)。但是我認(rèn)為這是用戶進(jìn)行測(cè)試和調(diào)試時(shí)的重要語(yǔ)義元素。像對(duì)象一樣的普通數(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對(duì)象的原型特別有趣,因?yàn)樗荗bject而不是預(yù)期的jQuery.fn.init,而且[0]表示某些東西,因?yàn)檫@是您在獲取時(shí)得到的。console.dir([])// outputs Array[0] as the object name or Array[x] x being the internal length of the// Array我不知道jQuery如何將它的原型設(shè)置為Object [0],但我的猜測(cè)是答案就在那兒。任何人有任何想法嗎?
2 回答

慕桂英3389331
TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊
該對(duì)象必須具有l(wèi)ength和splice
> var x = {length:2, '0':'foo', '1':'bar', splice:function(){}}
> console.log(x);
['foo', 'bar']
和FYI,Object[0]作為原型的原因完全相同。瀏覽器將原型本身視為數(shù)組,因?yàn)椋?/p>
$.prototype.length == 0;
$.prototype.splice == [].splice;

泛舟湖上清波郎朗
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
像這樣?
function foo() {
this.push('hello');
}
foo.prototype = [];
var bar = new foo();
console.log(bar.length); // 1
console.log(bar); // ["hello"]
添加回答
舉報(bào)
0/150
提交
取消