JavaScript:03基础部分2.3

042 Introduction to Objects

本讲主要学习对象。

视频加载中...

先复习下数组,定义jonasArray数组。

const jonasArray = [
	'Jonas',
	'Schmedtmann',
	2037 - 1991,
	'teacher',
	['Michael', 'Peter', 'Steven']
];

数组中每一项内容,不能用名字来引用,只能通过数组索引来使用。通过另外一种数据结构对象可以解决。对象是通过键值对来匹配的。

定义jonas对象。

const jonas = {
	firstName: 'Jonas',
	lastName: 'Schmedtmann',
	age: 2037 - 1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven']
};

通过数组和对象的定义的形式上比较,它们的区别有两点。方括号变成花括号,数组元素前多了冒号和名称。

在对象定义中,冒号左边称为键,冒号右边称为值。

对象花括号内键称为对象的属性,值称为对象的属性值。

数组和对象最大的区别在于,对象内的属性没有顺序约束。而数组必须保持顺序来使用。

043 Dot vs. Bracket Notation

本讲主要学习对象中的点和括号作用。

视频加载中...

上节课,我们学习了对象的定义。

const jonas = {
	firstName: 'Jonas',
	lastName: 'Schmedtmann',
	age: 2037 - 1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven']
};
console.log(jonas);

在控制台输出:

{firstName:"Jonas", lastName:"Schmedtmann", age: 46, job:"teacher", friends:Array(3)}

展开内容:

age:46
firstName:"Jonas"
friends:(3)["Michael", "Peter", "Steven"]
job:"teacher"
lastName:"Schmedtmann"

对象的属性按照字母顺序排序展示。

从对象中获取属性值使用点表示法。

jonas.lastName可以获取属性值Schmedtmann。

从对象中获取属性值使用方括号表示法。

jonas['lastName']可以获取属性值Schmedtmann。

在对象中使用方括号,方括号内可以用表达式来进行复杂地操作。

const nameKey = 'Name';
console.log(jonas['first' + nameKey]);
console.log(jonas['last' + nameKey]);

firstName和lastName属性名称,通过字符串拼接完成。

在控制台输出:

Jonas
Schmedtmann

对于点运算符,无法像方括号中使用表达式,必须使用确定的属性。

const interestedIn = prompt('What do you want to know about Jonas? Choose between firstName, lastName, age, job, and friends');
console.log(interestedIn);

在控制台弹出窗口,输入job,则控制台输出:

job

使用点运算符,看下jonas.job的结果。

console.log(jonas.interestedIn);

在控制台弹出窗口,输入job,控制台输出:

undefined

控制台输出结果与预期不符。这是为什么呢?

因为jonas.interestedIn只能识别为对象jonas匹配interestedIn属性,匹配不到,所以提示undefined。

使用点运算符不会把interestedIn识别为用户输入的值job。

这种情况需要使用方括号来操作。

console.log(jonas[interestedIn]);

在控制台弹出窗口,输入job,控制台输出:

teacher

如果在弹出窗口内输入的值与jonas内的属性相匹配,则得到对应属性值,否则得到undefined值。

根据undefined为假的情况,可以作为判断来输出一些说明。

const interestedIn = prompt('What do you want to know about Jonas? Choose between firstName, lastName, age, job, and friends');
if (jonas[interestedIn]) {
	console.log(jonas[interestedIn]);
} else {
	console.log('Wrong request! Choose between firstName, lastName, age, job, and friends');
}

在控制台弹出窗口,输入location,控制台输出:

Wrong request! Choose between firstName, lastName, age, job, and friends

在控制台弹出窗口,输入job,控制台输出:

teacher

接下来,学习向已知对象中添加属性和值。

jonas.location = 'Portugal';
jonas['twitter'] = '@jonasschmedtman';
console.log(jonas);

在控制台输出:

age:46
firstName:"Jonas"
friends:(3)["Michael", "Peter", "Steven"]
job:"teacher"
lastName:"Schmedtmann"
location:"Portugal"
twitter:"@jonasschmedtman"

044 Object Methods

本讲主要学习对象的内置方法this的使用。

视频加载中...

在对象中有键值相对应。对于值,也可以使用函数。

const jonas = {
	firstName: 'Jonas',
	lastName: 'Schmedtmann',
	birthYear: 1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven'],
	hasDriversLicense: true,
	calcAge: function (birthYear) {
		return 2037 - birthYear;
	}
};
console.log(jonas.calcAge(1991));

在控制台输出:

46
console.log(jonas['calcAge'](1991));

在控制台输出:

46

对于函数值的键值对,对象可以通过点运算符和方括号来操作对象属性。

在对象使用点或者方括号访问calcAge函数的时候,传入的参数1991实际上在对象中已经存在,那么在对象的calcAge函数中,直接调用1991所对应的属性即可。

const jonas = {
	firstName: 'Jonas',
	lastName: 'Schmedtmann',
	birthYear: 1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven'],
	hasDriversLicense: true,
	calcAge: function ( ) {
		console.log(this);
		return 2037 - this.birthYear;
	}
};
console.log(jonas.calcAge());

在控制台输出:

{firstName:"Jonas", lastName:"Schmedtmann", birthYear:1991, job:"teacher", friends:Array(3), ...}
46

在对象函数中,this在控制台打印出来的信息是整个对象内容,this代表整个对象,所以this.birthYear指的是1991。

在对象内部使用this来代表整个对象,仍然是为了简化代码,减少不必要的重复操作。如果把this替换为对象名称jonas,那么当对象名称改变的时候,对象内的对象名称也要更新,而使用this无需多余的操作来同步更新。

对于对象内的函数调用,如果重复使用,会多次重复计算,有没有方法,可以减少计算量,只计算一次?

当然可以,将函数的计算结果保存在对象新属性中,当使用的时候直接检索。

const jonas = {
	firstName: 'Jonas',
	lastName: 'Schmedtmann',
	birthYear: 1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven'],
	hasDriversLicense: true,
	calcAge: function ( ) {
		this.age = 2037 - this.birthYear;
		return this.age;
	}
};
console.log(jonas.calcAge());
console.log(jonas.age)
console.log(jonas.age)
console.log(jonas.age)

在控制台输出:

46
46
46
46

在函数体,通过this.age给对象jonas增加新属性age。后续就可以重复使用age属性,不必再使用函数调用。

挑战一句话,通过调用对象jonas内的属性来完成。

const jonas = {
	firstName: 'Jonas',
	lastName: 'Schmedtmann',
	birthYeah: 1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven'],
	hasDriversLicense: true,
	calcAge: function () {
		this.age = 2037 - this.birthYear;
		return this.age;
	},
	getSummary: function () {
		return `${this.firstName} is a ${this.calcAge()}-year old ${jonas.job}, and he has ${this.hasDriversLicense ? 'a' : 'no'} driver's license.`
	}
};
console.log(jonas.getSummary());

在控制台输出:

Jonas is a 46-year old teacher, and he has a driver's license.

045 Coding Challenge #3

本讲主要完成编码练习。

视频加载中...

Let's go back to Mark and John comparing their BMIs! This time, let's use objects to implement the calculations! Remember: BMI = mass / height ** 2 = mass / (height * height). (mass in kg and height in meter)

1. For each of them, create an object with properties for their full name, mass, and height (Mark Miller and John Smith)

2. Create a 'calcBMI' method on each object to calculate the BMI (the same method on both objects). Store the BMI value to a property, and also return it from the method.

3. Log to the console who has the higher BMI, together with the full name and the respective BMI. Example: "John Smith's BMI (28.3) is higher than Mark Miller's (23.9)!"

TEST DATA: Marks weights 78 kg and is 1.69 m tall. John weights 92 kg and is 1.95 m tall.

GOOD LUCK

本讲编码练习是使用对象来实现2个人的BMI的计算和比较。

1、创建对象,属性包含名称,体重,身高。

2、在对象中创建calcBMI方法计算BMI,存储BMI值到一个属性。

3、在控制台输出谁的BMI高,信息包含名称和BMI值。

编码实现参考如下。

const mark = {
	fullName: 'Mark Miller',
	mass: 78,
	height: 1.69,
	calcBMI: function () {
		this.bmi = this.mass / this.height ** 2;
		return this.bmi;
	}
};
const john = {
	fullName: 'John Smith',
	mass: 92,
	height: 1.95,
	calcBMI: function () {
		this.bmi = this.mass / this.height ** 2;
		return this.bmi;
	}
};
mark.calcBMI();
john.calcBMI();
console.log(mark.bmi, john.bmi);
// "John Smith's BMI (28.3) is higher than Mark Miller's (23.9)!"
if (mark.bmi > john.bmi) {
console.log(`${mark.fullName}'s BMI (${mark.bmi}) is higher than ${john.fullName}'s BMI (${john.bmi})`)
} else if (john.bmi > mark.bmi) {
console.log(`${john.fullName}'s BMI (${john.bmi}) is higher than ${mark.fullName}'s BMI (${mark.bmi})`)
}
展开阅读全文

页面更新:2024-02-21

标签:方括号   冒号   控制台   数组   函数   属性   定义   对象   名称   操作   基础

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top