1.JS变量
用var声明变量,例 var x;
可以在声明中规定变量类型,var s = new String;
也可以在声明过程中赋值, var s = "Hello World!"
变量的类型有五种:
var s =new String;
s = "Hello World!";
var x= new Number;
x = 10; 或者 x = 20.0; 或者 x = 10e2;//表示100
var y = new Boolen;
y = true; 或者 y = false;
/*数组越界会返回undefined*/
var arr = new Array(); //等同于var arr = [];
arr = [1,2,3];
赋值的时候可以在声明时就赋值 var arr = new Array(1,2,3);
*虽然一个Array数组可以存储不同类型的元素,但尽量不要如此,一个数组值存放一种数据类型的元素
/*数组可以动态加长*/
arr = [1, 2, 3];
arr[3] = 4;
//如果把数组名作为输出那么就是输出整个数组的所有值并默认用逗号分割
var person = new Object;
var person =
{
id : 9527,
firstname : "Bill",
lastname : "Gates"
};
或者:
var person = new Object();
person.firstname = "Bill";
person.lastname = "Gates";
person.id = 9527;
要用的时候就可以 var fn = person.firstname; 或者 var fn = person["firstname"];
附一段关于变量的代码:
<!DOCTYPE html>
<html>
<body>
<h1>My first JavaScript page (before)</h1>
<script>
var x = 1;
var s = "Hello World!";
var arr1 = new Array(x, s);
var arr2 = new Array;
arr2 = [s, x];
var ob =
{
id: 9527,
name: "Athrun"
}
var a = ob.id;
var b = ob["name"];
var arr3 = new Array(a,b);
function F()
{
document.write("<h1>My first JavaScript page (after)</h1>");
document.write("<h1>" + x + "</h1>" + "<br>");
document.write(s + "<br>");
document.write(arr1[0] + "<br>");
document.write(arr1[1] + "<br>");
document.write(arr2[0] + "<br>");
document.write(arr2[1] + "<br>");
document.write(arr3[0] + "<br>");
document.write(arr3[1] + "<br>");
}
</script>
<button type = "button" onclick = "F()">Click</button>
</body>
</html>
点击按钮之后