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

May 16, 2016 pm 03:41 PM
javascript

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles