一. 创建对象
Js的对象不需要有类,创建对象一般有两种方式,第一种:new Object();
<script type="text/javascript"> var obj = new Object(); obj.name = "张甲"; obj.age = 21; obj.gender = "男"; console.log(obj); //{name: "张甲", age: 21, gender: "男"} document.write(obj);[object Object] </script>
第二种:{属性名: 属性值,属性名: 属性值……}
<script type="text/javascript"> var obj = {name: "张甲", age: 21, gender: "男"}; console.log(obj); //{name: "张甲", age: 21, gender: "男"} document.write(obj);//[object Object] </script>
属性值还可以是一个js对象。
二. 创建数组
方法一:
<script type="text/javascript"> var names = new Array(); names[0]="小明"; names[1]="小红"; names[2]="小黑"; </script>
方法二:
<script type="text/javascript"> var names = ["小明","小红","小黑"]; document.write(names) //小明,小红,小黑 //输出数组大小 document.write(names.length) //3 //使用循环遍历 for (var i = 0; i < names.length; i++) { document.write(names[i]); } </script>
请登录之后再进行评论