---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net
JS中的数组 对象 ,如JAVA中的集合对象类似:
<body>
<script type="text/javascript">
var array = new Array("苹果","梨","香蕉");
for(var i in array)
{
document.writeln(i + " : " + array[i] + "<br>");
}
for(var i = 0 ; i < array.length ; i++)
{
document.writeln(i + " : " + array[i] + "<br>");
}
</script>
</body>
上面是一种数组对象的创建 及 两种数组对象的遍历方法。都可以达到目的。
<body>
<script type="text/javascript">
var array = new Array("苹果","梨","香蕉");
for(var i in array)
{
document.writeln(i + " : " + array[i] + "<br>");
}
for(var i = 0 ; i < array.length ; i++)
{
document.writeln(i + " : " + array[i] + "<br>");
}
with(document)
{
write("<font color = 'red'>ok</font>");
}
var arr = new Array(3);
arr[0] = "aa";
arr[1] = "bb";
arr[2] = "cc";
for(var i in arr)
{
document.writeln("<br>" + arr[i] )
}
var a = ["abc","def","ghk"];//推荐使用这种方式创建数组
for(var i in a)
{
document.writeln("<br>11 " + a[i] )
}
</script>
</body>
上面是几种在js中创建 数组的例子, var a = ["abc","def","ghk"];//推荐使用
这种方式创建数组 。
Js中的数组 既可以当作队列用 也可以当作栈来用。
s中的二维数组:
<body>
<script type = "text/javascript">
var array = new Array();
array[0] = new Array("aa","bb");
array[1] = ["cc","dd"];
for(var i = 0 ; i < array.length; i++)
{
for(var j = 0; j < array[i].length; j++)
{
document.write(array[i][j] + "<br>");
}
}
</script>
</body>
Document.write(“aa” + “bb” + “<br>”) == document.write(“aa”,”bb”,”
<br>”); 这两种方式是等价的。
下面是一个简单的js验证:
<script type="text/javascript">
function chec()
{
var str = document.getElementById("name").value;
if(str.indexOf("@") == -1)
{
alert("输入一个合法的email");
}
else
{
alert("ok!");
}
}
</script>
</head>
<body>
<form>
<input type = "text" name = "username" id = "name">
<input type = "submit" value = "check" onclick = "chec()">
</form>
</body>
下面是js中的对象的创建:
<body>
<script type = "text/javascript">
function person(name , age)
{
this.name = name;
this.age = age;
}
var p1 = new person("zhangsan",10);
var p2 = new person("lishi",20);
var p3 = new person("wangwu",30);
document.write(p1.name + " : " + p1.age + "<br>");
document.write(p2.name + " : " + p2.age+ "<br>");
document.write(p3.name + " : " + p3.age+ "<br>");
</script>
下面是为对象增加方法的方式:
<body>
<script type = "text/javascript">
function person(name , age)
{
this.name = name;
this.age = age;
this.display = display;
}
function display()
{
var str = this.name + " : " + this.age ;
document.write(str + "<br>");
}
var p1 = new person("zhangsan",10);
var p2 = new person("lishi",20);
var p3 = new person("wangwu",30);
p1.display();
p2.display();
p3.display();
</script>
</body>