javaScript - 对象的创建,对象的遍历

1.对象的创建方式

//方式1 字面量方式创建
var student = {
  id: 1,
  say: function (message) {
    console.log(message)
  }
}

//方式2 Object创建对象
var student=new Object();
student.id=1;
student.say=function (message) {
  console.log(message)
}

//方式3 构造函数的方式创建对象
function Student(id){
  this.id=id;
  this.say=function (message) {
    console.log(message)
  }
}
var student=new Student(1);

构造函数创建对象的方式 有跟java类的一些优点 推荐使用构造函数的方式创建对象

 

2.对象的遍历 获取名称与属性值

function Student(id){
  this.id=id;
  this.say=function (message) {
    console.log(message)
  }
}
var student=new Student(18)
//遍历对象
for(var key in student){
  console.log(key) // 获取名称
  console.log(student[key]) // 获取属性值
}

 

posted on 2023-02-06 21:52  Mikasa-Ackerman  阅读(10)  评论(0编辑  收藏  举报

导航