类(Classes)
在JavaScript中,类是一种创建对象的模板,它允许你定义一组属性和方法。自从ES6(ECMAScript 2015)引入类以来,JavaScript对象构造变得更加清晰和直观。
定义类
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
在这个例子中,Person 类有一个构造函数,它接受两个参数:name 和 age。每个 Person 对象都将具有这些属性。
创建实例
const person1 = new Person('Alice', 25);
const person2 = new Person('Bob', 30);
person1.sayHello(); // 输出: Hello, my name is Alice and I am 25 years old.
person2.sayHello(); // 输出: Hello, my name is Bob and I am 30 years old.
使用 new 关键字,你可以创建 Person 类的实例。
类的继承
JavaScript 支持类继承,这意味着你可以创建一个新的类,它继承自另一个类。
class Employee extends Person {
constructor(name, age, id) {
super(name, age); // 调用父类的构造函数
this.id = id;
}
getId() {
return this.id;
}
}
const employee = new Employee('Charlie', 35, 'E123');
console.log(employee.getId()); // 输出: E123
Employee 类继承自 Person 类,并添加了 id 属性和 getId 方法。
集合(Collections)
JavaScript 提供了几种内置的集合类型,如数组(Array)、映射(Map)和集合(Set),它们可以用来存储和操作数据。
数组(Array)
数组是一种有序的集合,它允许你存储多个值。
const fruits = ['Apple', 'Banana', 'Cherry'];
fruits.push('Date'); // 添加元素到数组的末尾
console.log(fruits); // 输出: ['Apple', 'Banana', 'Cherry', 'Date']
const firstFruit = fruits[0]; // 获取数组第一个元素
console.log(firstFruit); // 输出: Apple
映射(Map)
映射是一种键值对集合,它允许你使用任何类型的键。
const scores = new Map();
scores.set('Alice', 90);
scores.set('Bob', 85);
console.log(scores.get('Alice')); // 输出: 90
集合(Set)
集合是一种元素唯一的集合,它不允许重复的值。
const numbers = new Set([1, 2, 3, 4, 5, 5, 5]);
console.log(numbers.size); // 输出: 5
集合操作
JavaScript 提供了许多方法来操作集合,例如:
filter:创建一个新数组,包含通过提供的函数实现的测试的所有元素。map:创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后的返回值。reduce:对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(n => n * 2);
console.log(doubledNumbers); // 输出: [2, 4, 6, 8, 10]
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 输出: 15
通过理解和使用JavaScript中的类与集合,你可以创建更加复杂和功能丰富的应用程序。希望这个指南能帮助你开始你的JavaScript编程之旅!
