自定义函数需要使用function关键字。语法如下:
function 函数名([参数列表]){
程序语句
...
[return 返回值;]
}
+
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function show(){//定义一个无参数,无返回值的函数
alert("今天天气好好啊")//弹出文本
}
</script>
</body>
</html>
使用内置函数来实现简单的加法计算器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript"></script>
function sum(){
var resultValue,irstValue secondYalae;//声明3个变量,不给初值
firstValue document myform first value;//把第一个文本框的值赋给firstVabe
secondValue = document.myform.second. value;//把第二个文本框的值赋给secondValue
resultValue = firstValue + secondValue ;//相加运算
document.myform.result.value = resultValue ;
//把值赋给结果文本框
}
</script>
</head>
<body style="font-size:12px;">
<form name="myform">
加数: <input type-"text" name="first" size=6>
被加数: <input type="text" name="second" size=6>
<input type-"button" onclick="sum()" value="求和"> input type-"text" name="result" size -6>
</form>>
</body>
</html>
在上面的代码中,document.myform. first.value得到first文本框对象的内容,document.myform.second. value得到second文本框对象的内容,"document.myform.result. value = document.myform. first.value + document .myform.second. value"是将加数与被加数求和,然后将和赋给result文本框对象的值,显示出来。
使用字符串的长度和属性
- 给定一个字符串如“abaasdffggghhjjkkgfddsssss3444343”,问题如下:
- 字符串的长度
- 取出指定位置的字符,如9
- 查找指定字符是否在以上字符串中存在,如i
- 替换指定的字符,如g替换为9等操作方法
- 截取指定开始位置到结束位置的字符串,如取得1-5的字符串
- 找出以上字符串中出现次数最多的字符和出现的次数
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script type="text/javascript"> //字符串对象 var str="abaasdffggghhjjkkgfddsssss3444343" console.log("该字符的长度是:"+str.length) console.log(str.charAt(6))//返回指定指标为6的字符 console.log(str.indexOf("6"))//返回指定字符出现的位置上 console.log(str.replace("s","9"))//把字符串中的s换做9 console.log(str.substr(0,5))//截取0-5指标字符abaasd </script> </body> </html>