当前位置:网站首页>JS prototype. slice. call(arguments); Convert pseudo array to array

JS prototype. slice. call(arguments); Convert pseudo array to array

2022-06-25 13:22:00 wendyTan10

( One ).Array.prototype.slice.call(arguments);

  1. slice(start, end) Method to extract a part of an array , And return the new array
// Read elements in the array :
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3); // [)  Left closed right open interval 
citrus  Results output :
["Orange", "Lemon"]
  1. call() Function is used to call the current function function, And can use the specified object at the same time obj As this execution function intra-function this Pointer reference .
var obj = {
    name: "wendy", age: 20};
function fun(a, b){
    
    console.log(this.name);    
    console.log(a);    
    console.log(b);    
}
//  change this Referenced as obj, Pass two parameters at the same time 
fun.call(obj, 12, true); //  Li Si  12 true

var args = [].slice.call(arguments, 0);

arguments Is an object, not an array , At best, it is a pseudo array , And there is no such thing on the prototype chain slice This method .
3. [] Itself is also an object . And the array prototype chain has this slice This method .

 /* The return value here is true*/
   [].slice === Array.prototype.slice;

adopt call Explicit binding to implement arguments Disguised slice This method

quote hanyuntao Of Array.prototype.slice.call() The share of

( Two ). The method of converting the actual parameters of a function into an array

Method 1 :var args = Array.prototype.slice.call(arguments);
Method 2 :var args = [].slice.call(arguments, 0);
Method 3

var args = []; 
for (var i = 1; i < arguments.length; i++) {
     
    args.push(arguments[i]);
}

Last , A general function converted into an array is attached

var toArray = function(s){
    
    //try Statement allows us to define code blocks for error testing at execution time .
   //catch  Statements allow us to define when  try  When an error occurs in a code block , Code block executed .
    try{
    
        return Array.prototype.slice.call(s);
    } catch(e){
    
        var arr = [];
        for(var i = 0,len = s.length; i < len; i++){
    
            //arr.push(s[i]);
               arr[i] = s[i];  // It is said that this is more than push fast 
        }
         return arr;
    }
}
原网站

版权声明
本文为[wendyTan10]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200525275573.html