1. 字符串:
<!DOCTYPE html> <html> <body> <script> var apple = "苹果"; var banana = "香蕉"; var orange = "橘子"; var name1 = "小明"; var name2 = "小红"; document.write(name1 + "说:老师我想吃" + apple + "<br>"); document.write(name2 + "说:老师我想吃" + banana + "和" + orange); </script> </body> </html>
2. 数值
js中,数值类型比较简单,不区分整型浮点型等数字类型。就是这个数,带不带小数点,对js来说都是一样进行识别。
<!DOCTYPE html>
<html>
<body>
<script>
var a = 1;
var b = 2.3;
var c = a + b;
var name1 = "小明";
var name2 = "小红";
document.write(name1 + "问" + name2 + ":" + a + "+" + b + "等于几呀?" + "<br>");
document.write(name2 + "回答说:" + a + "+" + b + "等于" + c + "呀!" + "<br>");
</script>
</body>
</html>
难道js中,字符串和数值可以直接相加进行拼接吗?
实验:
<!DOCTYPE html>
<html>
<body>
<script>
var a = 1;
var b = 2.3;
var c = a + b;
var name1 = "小明";
var name2 = "小红";
document.write(name1 + "问" + name2 + ":" + a + "+" + b + "等于几呀?" + "<br>");
document.write(name2 + "回答说:" + a + "+" + b + "等于" + c + "呀!" + "<br>");
document.write(a + name1 + b + name2);
</script>
</body>
</html>
结果:
小明问小红:1+2.3等于几呀?
小红回答说:1+2.3等于3.3呀!
1小明2.3小红
可以的。
3. 布尔类型
真和假,分别用true和false表示。
4. 数组
<!DOCTYPE html> <html> <body> <script> // 方法1 var i; var cars1 = new Array(); cars1[0] = "Audi"; cars1[1] = "BMW"; cars1[2] = "Volvo"; for (i=0;i<cars1.length;i++) { document.write(cars1[i] + "<br>"); } document.write("<br>"); // 方法2 var cars2 = new Array("Audi", "BMW", "Volvo"); for (i=0;i<cars2.length;i++) { document.write(cars2[i] + "<br>"); } </script> </body> </html>
结果:
Audi
BMW
Volvo
Audi
BMW
Volvo
5. JavaScript对象
<!DOCTYPE html>
<html>
<body>
<script charset = "utf-8">
var info = {
name: "小明",
age: 63,
addr: "象牙山村156号",
}
// js对象有两种寻址方式
// 寻址1
document.write(info.name + "<br>");
// 寻址2
document.write(info["addr"] + "<br>");
</script>
</body>
</html>
一开始运行出来,中文是乱码,在<script charset = "utf-8">中,加入charset = "utf-8"后,解决了。