Home Web Front-end JS Tutorial arguments in javascript

arguments in javascript

Dec 14, 2016 am 09:28 AM
javascript

Although

function aaa(sTemplate) {  
var args = arguments;  
var s = sTemplate;
  s = s.replace(/\%\%/g, "%");
  for (var i = 1; i < args.length; i++)     
  s = s.replace( new RegExp("\%" + i + "\%", "g"), args[i] )
  return s;}
Copy after login

arguments is not an array, it can be used as an array. The subscript starts from 0, so:

arguments[0] represents the first parameter received

arguments[1] represents the second parameter received

...

And so on...

In this way, the same function can be called with different parameters~

Of course, the premise is that the function sets the processing method for the parameter, otherwise it will be in vain

arguments attribute

is The currently executing function object returns an arguments object.

function.arguments

function parameter is the name of the currently executing function and can be omitted.

The length property of the arguments object contains the number of arguments passed to the function. The access method for a single parameter contained in the arguments object is the same as that for the parameters contained in the array.

excerpted an example to illustrate the usage of arguments attribute. You can make the following reference:

function ArgTest(){
   var i, s, numargs = arguments.length;
   s = numargs; 
   if (numargs < 2){
      s += " argument was passed to ArgTest. It was ";
   }else{
      s += " arguments were passed to ArgTest. They were " ;
   }
   for (i = 0; i < numargs; i++){
         s += arguments[i] + " ";
   }
   return(s);
}
Copy after login

Quote:

1. Clever use of arguments

There is an array-like object named arguments in the Javascript function. It seems so weird and unknown, but numerous Javascript libraries use its powerful features. Therefore, its features require every Javascript programmer to be familiar with it.

In each function, there is a variable named arguments, which saves the parameters of the current call in an array-like form. And it is not actually an array. Trying to use the typeof arguments statement will return "object" (object), so it cannot use methods such as push and pop like Array. Even so, its value can still be obtained using the subscript and the length attribute.

2. Write flexible functions

Although it seems unknown, arguments are indeed very useful objects. For example, you can have a function handle a variable number of arguments. In the base2 library written by Dean Edwards, there is a function called format that takes full advantage of this feature:

function format(string) {
  var args = arguments;
  var pattern = new RegExp("%([1-" + arguments.length + "])", "g");
  return String(string).replace(pattern, function(match, index) {
    return args[index];
  });
};
Copy after login

The second parameter of the replace function can be a function, and the first parameter of the function can be match. The text of The parameters will replace these places in turn. For example:

format("And the %1 want to know whose %2 you %3", "papers", "shirt", "wear");

The above script will return

"And the papers want to know whose shirt you wear".

What needs to be noted here is that even in the format function definition, we only define a parameter named string. Javascript allows us to pass any number of parameters to a function, regardless of the number of parameters defined by the function itself, and save these parameter values ​​​​in the arguments object of the called function.

3. Convert to an actual array

Although the arguments object is not a real Javascript array, we can use the slice method of the array to convert it into an array, similar to the following code

var args = Array.prototype .slice.call(arguments);

call(obj, parameter list used by the current function)

The first parameter of the call method is an object, and the object passed in will call the slice function. Because arguments is not an array, so The slice method cannot be called directly, so the "object impersonation" method can only be used

In this way, the array variable args contains the values ​​contained in all arguments objects.

4. Make the parameters construct the function

Using the arguments object can reduce the amount of Javascript code we write. Below is a function called makeFunc that returns an anonymous function based on the function name you provide and any number of other parameters. When this anonymous function is called, the parameters of the original call are merged and passed to the specified function to run and then return its return value.

function makeFunc() {
  var args = Array.prototype.slice.call(arguments);
  var func = args.shift();
  return function() {
    return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));
  };
}
Copy after login

arguments has a non-enumerable attribute callee (cannot be read with for in, can be judged by HasOwnProterty (name)), arguments.callee is the Function object being executed. The current function pointer has been copied when slicing, so the first element of args is the function type. The first parameter of makeFunc specifies the name of the function to be called (yes, there is no error checking in this simple example). Remove from args after retrieval. makeFunc returns an anonymous function that calls the specified function using the Function Object's apply method. The first parameter of the

apply method specifies the scope. Basically the scope is the function being called. But that looks a bit complicated in this example, so we set it to null ; its second parameter is an array that specifies the parameters of the function it calls. makeFunc converts its own arguments and concatenates the arguments of the anonymous function before passing them to the called function.

有种情况就是总是要有个输出的模板是相同的,为了节省每次是使用上面提到的 format 函数并指定重复的参数,我们可以使用 makeFunc 这个工具。它将返回一个匿名函数,并自动生成已经指定模板后的内容:

var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1.");

你可以像这样重复指定 majorTom 函数:

majorTom("stepping through the door");

majorTom("floating in a most peculiar way");

那么当每次调用 majorTom 函数时,它都会使用第一个指定的参数填写已经指定的模板。例如上述的代码返回:

"This is Major Tom to ground control. I'm stepping through the door."

"This is Major Tom to ground control. I'm floating in a most peculiar way."

五、自引用的函数

您可能会认为这很酷,先别急着高兴,后面还有个更大的惊喜。它(arguments)还有个其他非常有用的属性:callee 。arguments.callee 包含了当前调用函数的被引用对象。那么我们如何使用这玩意做些的事情?arguments.callee 是个非常有用的调用自身的匿名函数。

下面有个名为 repeat 的函数,它的参数需要个函数引用和两个数字。第一个数字表示运行的次数,而第二个函数定义运行的间隔时间(毫秒为单位)。下面是相关的代码:

function repeat(fn, times, delay) {
  return function() {
    if(times-- > 0) {
      fn.apply(null, arguments);
      var args = Array.prototype.slice.call(arguments);
      var self = arguments.callee;
      setTimeout(function(){self.apply(null,args)}, delay);
    }
  };
}
Copy after login

repeat 函数使用 arguments.callee 获得当前引用,保存到 self 变量后,返回个匿名函数重新运行原本被调用的函数。最后使用 setTimeout 以及配合个匿名函数实现延迟执行。

作为个简单的说明,比如会在通常的脚本中,编写下面的提供个字符串并弹出个警告框的简单函数:

function comms(s) {
  alert(s);
}
Copy after login

好了,后来我改变了我的想法。我想编写个“特殊版本”的函数,它会重复三次运行每次间隔两秒。那么使用我的 repeat 函数,就可以像这样做到:

var somethingWrong = repeat(comms, 3, 2000);

somethingWrong("Can you hear me, major tom?");

结果就犹如预期的那样,弹出了三次警告框每次延时两秒。

最后,arguments 即便不会经常被用到,甚至显得有些诡异,但是它上述的那些惊艳的功能(不仅仅是这些!)值得你去了解它。

undefined ≠ null

null是一个对象,undefined是一个属性、方法或变量。存在null是因为对象被定义。如果对象没有被定义,而测试它是否是null,但因为没有被定义,它无法测试到,而且会抛出错误。

if(myObject !== null  && typeof(myObject) !== &#39;undefined&#39;) {
//如果myObject是undefined,它不能测试是否为null,而且还会抛出错误
}
if(typeof(myObject) !== &#39;undefined&#39; && myObject !== null) {
//处理myObject的代码
}
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 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.

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

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

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

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).

See all articles