在 JavaScript 中,对象是一种复合数据类型,用于组织和存储多个键值对(属性和值)的集合。对象可以表示现实世界中的实体、抽象概念或任何具有属性和行为的事物。
以下是关于 JavaScript 对象的一些基本概念:
创建对象:
在 JavaScript 中,可以使用两种方式来创建对象:
- 使用对象字面量:
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
isStudent: false
};
- 使用构造函数和
new
关键字:
function Person(firstName, lastName, age, isStudent) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.isStudent = isStudent;
}
let person = new Person('John', 'Doe', 30, false);
访问对象的属性:
可以使用点号.
或方括号[]
来访问对象的属性:
console.log(person.firstName); // 输出 "John"
console.log(person['lastName']); // 输出 "Doe"
添加和修改属性:
person.email = 'john@example.com'; // 添加新属性
person.age = 31; // 修改属性值
删除属性:
delete person.isStudent;
对象的方法:
对象的属性可以包含函数,这些函数称为对象的方法:
let person = {
firstName: 'John',
lastName: 'Doe',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
console.log(person.fullName()); // 输出 "John Doe"
嵌套对象:
对象可以包含其他对象作为其属性:
let person = {
name: {
first: 'John',
last: 'Doe'
},
age: 30
};
console.log(person.name.first); // 输出 "John"
对象的遍历:
可以使用循环来遍历对象的属性:
for (let key in person) {
console.log(key + ': ' + person[key]);
}
this 关键字:
在对象的方法中,this
关键字引用了当前对象。
let person = {
firstName: 'John',
lastName: 'Doe',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
上述是一些关于 JavaScript 对象的基本概念和操作方式。对象是 JavaScript 中非常重要和基础的数据类型,它们被广泛用于组织和管理程序的数据和行为。
学习测试代码
//练习:在新生欢迎会上,你已经拿到了新同学的名单,请排序后显示:欢迎XXX,XXX,XXX和XXX同学!:
'use strict';
var arr = ['小明', '小红', '小王', '小绿']
arr.sort()
console.log(`hello world from ${arr[0]} ${arr[1]} ${arr[0]}`)
var xiaoming = {
name: '小明',
birth: 1990,
school: 'No.1 Middle School',
height: 1.70,
weight: 65,
score: null,
};
//尝试输出对象不存在的属性
console.log(xiaoming)
console.log(xiaoming.height ,xiaoming.good)
//体会js是一种动态类型的脚本语言
xiaoming.number=10
console.log(xiaoming.number)
//使用关键字删除动态属性
delete xiaoming['number']
console.log(xiaoming.number)
//测试对象中是否有关键字
console.log()
console.log('name' in xiaoming);
console.log('number' in xiaoming)
//对象也存在继承关系,会向上继承object类
let property ='valueof';
let property1 ='toString';
let property2 ='name';
console.log(xiaoming.hasOwnProperty(property2));
运行结果
"C:\Program Files\nodejs\node.exe" C:\Users\Administrator\Desktop\Code\vuetest\main.js
hello world from 小明 小王 小明
{ name: '小明',
birth: 1990,
school: 'No.1 Middle School',
height: 1.7,
weight: 65,
score: null }
1.7 undefined
10
undefined
true
false
true
Process finished with exit code 0