JS函数参数传递

     在使用Js函数参数传递时,和其他编程语言一样,要注意是值传递还是引用(指针)传递。

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Tests</title>
<script language="javascript" type="text/javascript">
function alterArgs(strLiteral, argObject){
strLiteral = "override";
argObject[0] = 2;
argObject[1] = 3;
}

function testParams(){
var str = "origal";
var arg = new Array("two", "three");

document.writeln(str + "<br/>");
document.writeln(arg + "<br/>");
alterArgs(str, arg);
document.writeln(str + "<br/>");
document.writeln(arg + "<br/>");

}
</script>
</head>
<body onload = "testParams();">  
</body>
</html>

 

//运行结果:
//origal
//two,three
//origal
//2,3

    可以看到作为基本数据类型,字符串,是进行值传递的;而对于对象Array是进行引用传递的。

    下面再来看一个比较:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Tests</title>
<script language="javascript" type="text/javascript">
function alterArgs(strLiteral, argObject){
strLiteral = new Date();
argObject[0] = 2;
argObject[1] = 3;
}

function testParams(){
var str = new Date(55555555555);
var arg = new Array("two", "three");

document.writeln(str + "<br/>");
document.writeln(arg + "<br/>");
alterArgs(str, arg);
document.writeln(str + "<br/>");
document.writeln(arg + "<br/>");

}
</script>
</head>
<body onload = "testParams();">  
</body>
</html>
//运行结果:
//Wed Oct 06 1971 08:05:55 GMT+0800 (China Standard Time)
//two,three
//Wed Oct 06 1971 08:05:55 GMT+0800 (China Standard Time)
//2,3

你可能感兴趣的:(参数传递)