Array.prototype.slice.call(arguments)



Array Prototype Slice



多くの場合、Array.prototype.slice.call(arguments)などのArray.prototype.slice.call()メソッドをよく目にします。原理について話しましょう:

1、基本的な説明

  • 1. JSでは、Arrayはクラスです。スライスはこのクラスのメソッドです。次に、このメソッドを使用してArray.prototype.sliceを使用します。
    スライスは文字通り理解しやすい傍受です(もちろんあなたは英語ではありません)この方法の使い方は?
    arrayObj.slice(start, [end])明らかにアレイの一部を傍受しています。



  • 2.もう一度電話を見てみましょう。

call([thisObj[,arg1[arg2[[argN]]]]])

thisObjはオブジェクトメソッドです
arrg1〜argNはパラメータです



次にArray.prototype.slice.call(arguments,1)この文の意味は、呼び出し元のメソッドのパラメーターをインターセプトすることです。
といった:

function test(a,b,c,d) { var arg = Array.prototype.slice.call(arguments,1) alert(arg) } test('a','b','c','d') //b,c,d

2、疑問と答え

最初に例を挙げてください。これはjqFloatプラグインのコードです。

if (element.data('jDefined')) { if (options && typeof options === 'object') { methods.update.apply(this, Array.prototype.slice.call(arguments, 1)) } } else { methods.init.apply(this, Array.prototype.slice.call(arguments, 1)) }

Array.prototype.slice.call(arguments、1)を複数回使用すると、arguments.slice(1)と同じではありませんか?前者のように書くことの具体的な利点は何ですか?これは、多くの新しいjs初心者にとって最も疑わしい場所です。それでなんで?



引数は実際には配列のように配列オブジェクトではないため、sliceメソッドはありません。Array.prototype.slice.call(arguments, 1)引数は配列オブジェクトに変換されるため、引数にslice()メソッドを持たせます。直接arguments.slice(1)を書くと、エラーが発生します。

Typeof arguments==='Object' //not 'Array'

3、本当の原則

Array.prototype.slice.call(arguments) IEで設定されたノードを除いて、length属性を持つオブジェクトを配列に変換できます(ieでのdomオブジェクトはcomオブジェクトとして実装されているため、jsオブジェクトとcomオブジェクトは変換できません)
といった:

Var a={length:2,0:'first',1:'second'}// class array, length attribute, length 2, 0 is first, the first is second Console.log(Array.prototype.slice.call(a,0))// ['first', 'second'], calling array(0) of the array var a={length:2,0:'first',1:'second'} Console.log(Array.prototype.slice.call(a,1))//['second'], calling array(1) of the array Var a={0:'first',1:'second'}//remove the length attribute, return an empty array console.log(Array.prototype.slice.call(a,0))//[] function test(){ console.log(Array.prototype.slice.call(arguments,0))//['a', 'b', 'c'],slice(0) console.log(Array.prototype.slice.call(arguments,1))//['b', 'c'],slice(1) } test('a','b','c')

補足:
関数の実際の引数を配列に変換する方法

方法1:var args = Array.prototype.slice.call(arguments)

方法2:var args = [].slice.call(arguments, 0)

方法3:

var args = [] for (var i = 1 i

最後に、配列に変わるジェネリック関数をアタッチします

var toArray = function(s){ try{ return Array.prototype.slice.call(s) } catch(e){ var arr = [] for(var i = 0,len = s.length i

著作権表示:この記事はXiao Pingguoの元の記事です。以下を示してください:http://blog.csdn.net/i10630226