1.全局函数
(1)encodeURI(URIstring):以UTF-8编码字符串,但对字符串中‘;,:#@=+&’不做编码
(2)decodeURI(URIstring):对用encodeURI方法编码的字符创进行解码
(3)encodeURIComponent(URIstring):以UTF-8编码字符串,字符串中所有字符都被编码
(4)decodeURIComponent(URIstring):对于用(3)编码的进行解码
(5)escpe(string):使用16进制进行编码
(6)unescape():对用(5)进行解码
(7)parseFloat(string):解析一个字符串并返回一个浮点型
(8)parseInt(String)解析字符串返回一个整数
(9)eval(string):计算Javascript字符串,当做脚本使用
(10)ifFinite(number):判断参数是否有限
例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>编码与解码函数</title>
</head>
<body>
<script type="text/javascript">
var url1="https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index/章"
var enurl1=encodeURI(url1);
var enurl2=encodeURIComponent(url1);
var enurl3=escape(url1);
document.write("<br> encodeURI编码后为:"+enurl1);
document.write("<br>解码后为:"+encodeURI(enurl1)+"<br>");
document.write("<br>encodeURIComponent:"+decodeURIComponent(enurl2)+"<br>");
document.write("<br> escape:"+unescape( enurl1));
</script>
</html>
2.用户自定义函数
(1)函数的定义与调用
function 函数名(形参){
函数体;
return;或者return 表达式;
}
调用 函数名(实参)
例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>弹出下拉列表</title>
</head>
<style>
#stationList{
display: none; /* 点击显示 */
margin-left: 70px;
}
fieldset{
padding: 20px;
width: 200px;
margin: 0 auto; /* 居中 */
}
#fromStation{
width: 100px;
}
</style>
<body>
<fieldset>
<legend>余票查询</legend>
<label>出发地:</label>
<input placeholder="简码/汉字" id ="fromStation"onclick="showSelect()" ><br>
<select id="stationList" size="5" onclick="setText(this,'fromStation')">
<option>上海</option>
<option>北京</option>
<option>天津</option>
<option>重庆</option>
</select>
</fieldset>
</body>
<script type="text/javascript">
function showSelect(){
document.getElementById("stationList").style.display="block";
}
function setText(selectobj,textId){
document.getElementById(textId).value=selectobj.options[selectobj.selectedIndex].text;
}
</script>
</html>
(2)匿名函数
window.onload=function(){
函数体;
return;
}
(3)嵌套函数
function 函数1(){
函数体;
function 函数2(){
}
函数2;
}
函数1()
(4)函数做参数
function funl(thefun2){
thefun2();
}
function fun2(){
}
fun1(fun2);
(5)参数可变的函数
JavaScript中每个函数都具有一个arguments对象,该对象会接受调用函数传递过来的实际参数,arguments[0]对应第一个参数
arguments[2]对应第二个参数,以此类推,因此形参列表可以为空或者实参个数超过形参个数。
arguments中有两个属性 callee与caller
(1)callee:获取当前函数
(2)caller:获取父级函数(嵌套函数,若为顶级 则caller为空)
例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>arguments对象的caller与callee属性使用</title>
</head>
<body>
<script type="text/javascript">
function calleeDemo(){
alert(arguments.callee) //获取正在执行函数
}
function callerDemo() {
if(callerDemo.caller){ //true 打印
var a=callerDemo.caller.arguments[0];
alert(a);
}else{
alert("this is a top function");
}
}
function handleCaller() {
callerDemo();
}
calleeDemo();
callerDemo();
handleCaller("参数1","参数2");
</script>
</body>
</html>