<分区>
我是 jquery 的新手,基本上,我只是在查看 jquery 中 get()
函数的源代码,它看起来像下面这样 (Jquery 11.1.3):
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
现在我理解了这个函数的大部分,我已经使用我对 js 的基本理解来理解这个函数在做什么,这是我的想法,return 语句是一个三元运算符,它将检查 num
是负数或正数(即 num < 0),并将得出给定条件,
如果 num
是负数 this[ num + this.length ]
否则返回
this[ num ]
将被退回,好的,很公平,现在是什么部分:
slice.call( this );
在这个函数中做什么?
我假设它正在将一个对象转换为一个数组,以防你传递一个对象而不是一个纯数组,我做了以下函数来证明我自己的观点:
function get(elem) {
return Array.prototype.slice.call( elem );
}
obj = {
'name' : 'putin',
'sname' : 'valdimar'
}
var str = get(obj);
console.log(str); // returns empty array.
如您所见,str
是一个空数组,而不是转换为纯数组的对象。所以我想我遗漏了一些非常微不足道的东西,但是现在有人可以详细说明并理解 slice.call(this)
在 jquery 的 get()
方法中做了什么吗?