Home > Web Front-end > JS Tutorial > A brief discussion on the Array.prototype.slice.call_javascript technique of javascript

A brief discussion on the Array.prototype.slice.call_javascript technique of javascript

WBOY
Release: 2016-05-16 15:41:39
Original
1094 people have browsed it

Before writing

In js, we often see the writing method Array.prototype.slice.call(arguments,0). Of course, everyone may understand the role of this method, which is to convert an array-like object into a real array. Regarding this method, let me talk about my understanding.

This involves the slice() method and the call() method, so let’s briefly talk about these two methods first.

slice() method

Arrays and strings both have this slice method. The function of this method is to intercept a piece of data. It receives two parameters. The first parameter is the position index to be intercepted. The second parameter is optional and indicates the end position to be intercepted, but does not include the end position. In an array, the return value of this method is an array containing the intercepted elements. In a string, the return value of this method is a string containing the intercepted string.

This method can also pass in negative values. When the parameter is a negative number, the positive number obtained by adding the parameter and the length of the array or string is used as the actual parameter.

is as follows:

[1,2,3,4,5,6].slice(2,4);

[1,2,3,4,5,6].slice(-4,-2);

Copy after login

The return values ​​are all [3,4], which are arrays.

'everything'.slice(2,4);

'everything'.slice(-4,-2);

Copy after login

The return values ​​are 'er' and 'hi' respectively, which are strings.

If a parameter is passed in, all elements from the start position to the end position will be output. No more examples.

Other similar methods for strings

In strings, there are two other methods of type slice():

substring() and substr() methods.

Among them, the substring() method means returning a string from the start position to the end position. substr() receives two parameters. The first parameter indicates the starting position, and the second parameter indicates the number of characters to be intercepted, and The first two methods are slightly different.

When the parameter passed into the method is a negative number, these three methods are slightly different.

When the parameter passed into the method is a negative number:

slice(), as mentioned above, adds the negative number to the length of the string to get the corresponding positive value;

The parameters of the substring() method are all set to zero;

The first parameter of the substr() method is a positive value obtained by adding the negative value plus the length of the string, and the second parameter is set to zero.

call() and apply() methods

The call() and apply() methods are mainly used to expand the scope of the function.

The call() and apply() methods receive two parameters:

apply(): The first parameter is the scope, and the second is the parameter array. The second parameter can be an array instance or an arguments object.

The call() method also receives two parameters, but the method of passing parameters is different from apply(): the parameters of the passed function must be written one by one.

Since this is not the focus, I won’t go into details here.

Array.prototype.slice.call(arguments,0)
Copy after login

In Array.prototype.slice.call(arguments,0), ​​Array.prototype.slice calls the prototype method of Array. For real arrays, there is the slice() method, but for things like arguments or self-defined Although some array-like objects have several attributes such as length, they do not have a slice() method. Therefore, for such array-like objects, you have to use the prototype method to use the slice() method, that is, Array.prototype.slice (if in customization The slice() method is customized in the array-like object, so it can be called directly).

So, the meaning of Array.prototype.slice.call(arguments,0) can be understood like this: for the arguments class array, we call the Array.prototype.slice prototype method and use the call() method to limit the scope to In arguments, Array.prototype here can be understood as arguments, and parameter 0 is the first parameter of the slice() method, which is the starting position index. In this way, the arguments class array is converted into a real array.

Of course, you can also use traversal to convert arguments into an array, so the code will naturally be more and not direct enough.

We know that Array.prototype.slice.call(arguments) can convert objects with length attributes into arrays, except for the node collection under IE (because the DOM object under IE is implemented in the form of a com object, js Objects and COM objects cannot be converted)
Such as:

 var a={length:2,0:'first',1:'second'};
 Array.prototype.slice.call(a);// ["first", "second"]
 var a={length:2};
 Array.prototype.slice.call(a);// [undefined, undefined]
Copy after login

Maybe those who have just started learning js don’t quite understand why this sentence can achieve such a function. For example, I am one, so let’s explore it.

First of all, slice has two usages, one is String.slice and the other is Array.slice. The first one returns a string, and the second one returns an array. Here we look at the second one.

Array.prototype.slice.call(arguments) can convert arguments into an array, then it is arguments.toArray().slice(); At this point, can we just say Array.prototype.slice.call(arguments) The process is to convert the first parameter passed in to an array and then call slice?

Let’s look at the usage of call again, as shown in the following example

 var a = function(){
   console.log(this);  // 'littledu'
   console.log(typeof this);   // Object
   console.log(this instanceof String);  // true
 }
 a.call('littledu');
Copy after login

可以看出,call了后,就把当前函数推入所传参数的作用域中去了,不知道这样说对不对,但反正this就指向了所传进去的对象就肯定的了。
到这里,基本就差不多了,我们可以大胆猜一下slice的内部实现,如下

 Array.prototype.slice = function(start,end){
   var result = new Array();
   start = start || 0;
   end = end || this.length; //this指向调用的对象,当用了call后,能够改变this的指向,也就是指向传进来的对象,这是关键
   for(var i = start; i < end; i++){
      result.push(this[i]);
   }
   return result;
 }

Copy after login

大概就是这样吧,理解就行,不深究。

最后,附个转成数组的通用函数

var toArray = function(s){
  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]; //据说这样比push快
      }
       return arr;
  }
}
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template