深入理解JS函数的参数(arguments)的使用

JavaScript08

深入理解JS函数的参数(arguments)的使用,第1张

JS函数的参数在function内可以用arguments对象来获取。

参数的调用有两种方式:

1、期望参数的使用。

2、实际传递参数的使用。

应用举例:

function

Test(a,

b){

var

i,

s

=

"Test函数有"

var

numargs

=

arguments.length

//

获取实际被传递参数的数值。

var

expargs

=

Test.length

//

获取期望参数的数值,函数定义时的预期参数个数(有a和b

2个参数)。

s

+=

(expargs

+

"个参数。")

s

+=

"\n\n"

for

(i

=0

i

<

numargs

i++){

//

获取参数内容。

s

+=

"

第"

+

i

+

"个参数是:"

+

arguments[i]

+

"\n"

}

return(s)

//

返回参数列表。

}

alert(Test('param1','second

param','第三个参数'))

需要注意的是:

arguments是一个object对象,它不是数组,不能对它使用shift、push、join等方法。

上述举例时用的arguments[i]中的i只是作为arguments对象的属性,并不能理解为数组下标。

代码演示

<html>

<head>

<script

language="javascript">

function

reloadList(){

if(typeof

arguments[0]

==

"function"){

arguments[0].call(this)

arguments[0]()

}

if(typeof

arguments[0]

==

"string")

alert(arguments[0])

if(typeof

arguments[0]

==

"number")

alert(arguments[0])

if(typeof

arguments[0]

==

"undefined")

alert(arguments[0])

if(typeof

arguments[0]

==

"boolean")

alert(arguments[0])

if(typeof

arguments[0]

==

"null")

alert(arguments[0])

}

reloadList(function(){})

</script>

</head>

<body>

</body>

以上这篇深入理解JS函数的参数(arguments)的使用就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

伪数组(类数组):

无法直接调用数组方法或期望length属性有什么特殊的行为,不具有数组的push,pop等方法,但仍可以对真正数组遍历方法来遍历它们。典型的是函数的argument参数,还有像调用getElementsByTagName,document.childNodes之类的,它们都返回NodeList对象都属于伪数组。可以使用Array.prototype.slice.call(fakeArray)将数组转化为真正的Array对象。

function log(){

var args = Array.prototype.slice.call(arguments)//为了使用unshift数组方法,将argument转化为真正的数组

args.unshift('(app)')console.log.apply(console, args)

}

这里把符合以下条件的对象称为伪数组:

1,具有length属性

2,按索引方式存储数据

3,不具有数组的push,pop等方法

1,function内的arguments 。

2,通过document.forms,Form.elements,Select.options,document.getElementsByName() ,

document.getElementsByTagName() ,childNodes/children 等方式获取的集合(HTMLCollection,NodeList)等。

3,特殊写法的对象 ,如

Js代码 收藏代码

var obj={}

obj[0] = "一"

obj[1] = "二"

obj[2] = "三"

obj.length = 3