Home >Web Front-end >JS Tutorial >arguments in 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;}
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); }
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]; }); };
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))); }; }
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); } }; }
repeat 函数使用 arguments.callee 获得当前引用,保存到 self 变量后,返回个匿名函数重新运行原本被调用的函数。最后使用 setTimeout 以及配合个匿名函数实现延迟执行。
作为个简单的说明,比如会在通常的脚本中,编写下面的提供个字符串并弹出个警告框的简单函数:
function comms(s) { alert(s); }
好了,后来我改变了我的想法。我想编写个“特殊版本”的函数,它会重复三次运行每次间隔两秒。那么使用我的 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) !== 'undefined') { //如果myObject是undefined,它不能测试是否为null,而且还会抛出错误 } if(typeof(myObject) !== 'undefined' && myObject !== null) { //处理myObject的代码 }