JavaScript开发应用小实例

1.1输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"content="text/html;charset=UTF-8">
<title></title>
<body>
<input type="button" value="关闭窗口"onclick="window.close();"/>
<script type="text/javascript">
<!—
//输出方法
document.write("您好,现在时间为:"+newDate());
-->
</script>
</body>
</html>

(注:以后只写Scrip内部的东西;
注释在代码右边,极少在上面,绝不在下面)

2.1变量的赋值

1
2
3
4
var username = "Tom";//声明变量username并赋值"Tom"
var account = 4500; //声明变量account并赋值4500
age = 23; //未声明直接为变量age赋值23
var marriaged ; //声明变量marriaged未赋值

2.2变量的练习

1
2
3
4
5
6
var a = 3,b=5; //声明全局变量a
function add(x,y){ //这里参数x和y为局部变量
var c = 6; //局部变量c
return x + y;}
document.write("<h2>a + b =" + add(a,b)+"<h2>");
document.write("c的值为:" + c);//这里会发生错误,c的值未定义

2.3数据类型转换

1
2
3
4
5
var a; //声明变量a,因为没有赋值此值为undefined
var b = null;
var c = "100";
d = parseInt(c) + b; //c由字符转为数值
document.write("a转换为数值型的结果是:" + parseInt(a) +"<br/>");

2.4数据类型转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var a = undefined;
var b = null;
var str1 = "",str2 = "hello123"; //声明两个字符型变量,其值分别为空和"hello123"
var num1 = 0,num2 = NaN,num3=38; //声明三个数值型变量,其值分别为0,NaN和38
var obj = new Object(); //这里创建了一个对象,名称为obj
with(document){ //对象的with用法
write("undefined转换后的值为:"+ new Boolean(a) +"<br/>"); //将a转为布尔型false
write("null转换后的值为:"+ new Boolean(b) +"<br/><hr>"); //将b转为布尔型false
write("空字符串转换后的值为:"+ new Boolean(str1) +"<br/>"); //转为布尔型false
write("非空字符串转换后的值为:" + new Boolean(str2) +"<br/><hr>");//转为布尔型true
write("0转换后的值为:" + new Boolean(num1) +"<br/>");//转为布尔型false
write("NaN转换后的值为:" + new Boolean(num2) +"<br/>");//转为布尔型false
write("非0和NaN数值转换后的值为:" + new Boolean(num3) +"<br/><hr>");//转为布尔型true
write("对象转换后的值为:"+new Boolean(obj) +"<br/>"); //转为布尔型true
}

3.1算术运算符练习

1
2
3
4
5
6
7
8
9
10
var sum1 = 10,sum2 = 3;
result = "字符串" + sum1 + sum2; //结果为字符串
with(document){
write("<p>sum1= " + sum1 + " , sum2 = "+ sum2 + "<p/>"); //输出数值
write("<li>sum1+ sum2 = " + (sum1 + sum2) + "</li>");  //输出数值(加减乘除道理一样)
write("<li>sum1%sum2="+(sum1%sum2)+"</li>");//求余
write("<li>result= " + result + "</li>");
write("<li>++sum1="+++sum1+"</li>");//自加
write("<li>sum2--="+sum2--+"</li>");//自减
}

更多实例请看文档
http://osprtpxhb.bkt.clouddn.com/JavaScript%E5%BC%80%E5%8F%91%E5%BA%94%E7%94%A8%E5%B0%8F%E5%AE%9E%E4%BE%8B.docx

Mr.Naas wechat
欢迎关注本人公众号