javascript - slice.call() 在 get() jquery 函数中做什么

标签 javascript jquery

<分区>

我是 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() 方法中做了什么吗?

最佳答案

您的评估是正确的。 jQuery 对象是一个类似数组的对象,get正在将 jQuery 对象变成真正的数组。文档中对此进行了概述。

要使 slice 作用于数组以外的对象,该对象必须具有整数属性键。它还必须具有 length 属性:

Array.prototype.slice.call({ 0: 'foo', 1: 'bar', length: 2 })
// yields ['foo', 'bar']

或者更有趣的是:

Array.prototype.slice.call({ 45: 'foo', 47: 'bar', length: 48 })
// [undefined × 45, "foo", undefined × 1, "bar"]

关于javascript - slice.call() 在 get() jquery 函数中做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30986640/

相关文章:

javascript - 如何使用 JavaScript 删除 iFrame 中的 HTML 元素

javascript - 在不滚动的情况下加载当前 div 上方的新 Ajax 内容

javascript - 如何总结输入字段中输入的特定值?

javascript - 为什么我对 PostgreSQL DB 的发布请求将我的 UTC DATETIME 保存为本地时间

javascript - Twilio JavaScript - 从客户端到服务器的短信

javascript - 如何使用javascript设置H1的颜色?

jquery - 如何知道提交时点击了哪个提交输入?

javascript - ng-show 设置为 false 不会在页面加载时隐藏元素

jquery - 我应该加载整个 jQuery UI JS/CSS 还是只加载特定页面上我需要的部分?

javascript - 如何在单击按钮时运行功能?