每个开发者都应该掌握的基本 JavaScript 方法
各位工匠们好,
今天的博客文章将介绍 JavaScript ES6(ECMAScript 2015),它引入了大量新特性和语法增强功能,彻底改变了开发者编写 JavaScript 代码的方式。这些新增功能中包含许多简化常见任务和优化开发工作流程的方法。
那么,让我们深入了解一些最常用的 ES6 方法,并为每个方法提供实际示例。
1. map(
) 方法通过对原始数组的每个元素应用函数来创建一个新数组。
const numbers = [1, 2, 3, 4, 5];
const multiply= numbers.map(num => num * 2);
console.log(multiply); // Output: [2, 4, 6, 8, 10]
2. filter()
filter() 方法创建一个新数组,其中包含符合特定条件的元素。
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4]
3. reduce()
reduce() 方法对累加器和数组中的每个元素应用一个函数,将其减少为单个值。
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15
4. find()
find() 方法返回数组中满足给定测试函数的第一个元素。
const users = [
{ id: 1, name: 'Snehal' },
{ id: 2, name: 'Rajeev' },
{ id: 3, name: 'Moon' }
];
const user = users.find(user => user.id === 2);
console.log(user); // Output: { id: 2, name: 'Rajeev' }
5. includes()
方法 (Array.prototype.includes()) 确定数组是否包含某个值。
const numbers = [1, 2, 3, 4, 5, 14];
const includesFive = numbers.includes(5);
console.log(includesFive); // Output: true
6. includes()
类似地,includes() 方法(String.prototype.includes())可用于字符串,以检查是否存在子字符串。
const str = 'Hello Artisans!, I am Rajeev Moon.';
const isStringIncluded = str.includes('Artisans');
console.log(isStringIncluded ); // Output: true
7. Object.keys()
Object.keys() 方法返回给定对象自身可枚举属性名称的数组。
const person = {
name: 'Rajeev Moon',
age: 30,
job: 'Developer'
};
const keys = Object.keys(person);
console.log(keys); // Output: ['name', 'age', 'job']
8. Object.entries(
) 方法返回给定对象自身的可枚举字符串键属性 [key, value] 对的数组。
const person = {
name: 'Rajeev Moon',
age: 30,
job: 'Developer'
};
const entries = Object.entries(person);
console.log(entries); // Output: [['name', 'Rajeev Moon'], ['age', 30], ['job', 'Developer']]
9.箭头函数(=>)
一种简洁的编写匿名函数的方式,提供了更易读的语法和词法作用域。
const add = (a, b) => a + b;
10. 模板字面量
启用字符串插值和使用反引号的多行字符串。
// backticks (``)
const name = 'Rajeev Moon';
const greeting = `Hello, ${name}! nice to meet you.`;
console.log(greeting ); // Output: Hello Rajeev Moon nice to meet you.
11. 解构赋值
轻松地将数组和对象中的值提取到变量中。
const person = { name: 'Rajeev Moon', age: 30 };
const { name, age } = person;
12. 展开语法(...)
将数组或对象等可迭代对象展开为单个元素。
const numbers = [1, 2, 3];
const newNumberList = [...numbers, 4, 5];
console.log(newNumberList ); // Output: [1, 2, 3, 4, 5]
13. 剩余参数(...)
将剩余的函数参数收集到一个数组中。
function sum(...args) {
return args.reduce((acc, val) => acc + val, 0);
}
14. 对象字面量增强
定义对象属性的更简洁语法。
const x = 10, y = 20;
const point = { x, y }; // { x: 10, y: 20 }
这些只是众多 ES6 特性和方法中的一小部分,它们已经成为现代 JavaScript 开发不可或缺的一部分。
理解和运用这些 JavaScript 方法可以大大提高代码的可读性、可维护性和效率。
阅读愉快,编程愉快!! ❤️🦄
文章来源:https://dev.to/snehalkadwe/essential-javascript-es6-methods-every-developer-should-know-4fnk
