javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > ES6 新增 API

ES6 新增 API 方法示例详解

作者:超级土豆粉

ES6 引入了众多新特性和 API 方法,使 JavaScript 代码更加简洁、高效和易于维护,这些新增 API 极大地简化了开发流程,提高了代码质量,成为现代 JavaScript 开发的基础,这篇文章给大家介绍ES6新增API方法,感兴趣的朋友跟随小编一起看看吧

ES6 新增 API 方法

背景介绍

ECMAScript 6(简称 ES6)于 2015 年发布,带来了 JavaScript 语言的重大更新。ES6 引入了众多新特性和 API 方法,使 JavaScript 代码更加简洁、高效和易于维护。这些新增 API 极大地简化了开发流程,提高了代码质量,成为现代 JavaScript 开发的基础。

数组方法

1. Array.from()

// 类数组转数组
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 }
const arr = Array.from(arrayLike)
console.log(arr) // ['a', 'b', 'c']
// 带映射功能
const numbers = Array.from([1, 2, 3], x => x * 2)
console.log(numbers) // [2, 4, 6]
// Set转数组
const set = new Set(['a', 'b', 'c'])
const arrFromSet = Array.from(set)
console.log(arrFromSet) // ['a', 'b', 'c']

2. Array.of()

// 创建数组
const arr1 = Array.of(7)
console.log(arr1) // [7]
const arr2 = Array.of(1, 2, 3)
console.log(arr2) // [1, 2, 3]
// 对比Array构造函数
const arr3 = new Array(7)
console.log(arr3) // [empty × 7]

3. find/findIndex

const numbers = [1, 2, 3, 4, 5]
// find
const found = numbers.find(num => num > 3)
console.log(found) // 4
// findIndex
const foundIndex = numbers.findIndex(num => num > 3)
console.log(foundIndex) // 3
// 找不到时的返回值
const notFound = numbers.find(num => num > 10)
console.log(notFound) // undefined
const notFoundIndex = numbers.findIndex(num => num > 10)
console.log(notFoundIndex) // -1

4. includes

const array = [1, 2, 3, NaN]
// 基本使用
console.log(array.includes(2)) // true
console.log(array.includes(4)) // false
// 从指定位置开始查找
console.log(array.includes(1, 1)) // false
// 可以查找NaN
console.log(array.includes(NaN)) // true

5. flat/flatMap

// flat
const nested = [1, [2, 3], [4, [5, 6]]]
console.log(nested.flat()) // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2)) // [1, 2, 3, 4, 5, 6]
// flatMap
const sentences = ['Hello world', 'Good morning']
const words = sentences.flatMap(s => s.split(' '))
console.log(words) // ['Hello', 'world', 'Good', 'morning']

对象方法

1. Object.assign()

// 对象合并
const target = { a: 1 }
const source1 = { b: 2 }
const source2 = { c: 3 }
const result = Object.assign(target, source1, source2)
console.log(result) // { a: 1, b: 2, c: 3 }
// 浅拷贝
const original = { a: 1, b: { c: 2 } }
const copy = Object.assign({}, original)
console.log(copy) // { a: 1, b: { c: 2 } }

2. Object.keys/values/entries

const obj = { a: 1, b: 2, c: 3 }
// Object.keys()
console.log(Object.keys(obj)) // ['a', 'b', 'c']
// Object.values()
console.log(Object.values(obj)) // [1, 2, 3]
// Object.entries()
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
// 实际应用
Object.entries(obj).forEach(([key, value]) => {
  console.log(`${key}: ${value}`)
})

3. Object.getOwnPropertyDescriptors()

const obj = {
  get foo() {
    return 'foo'
  },
}
// 获取完整的属性描述符
console.log(Object.getOwnPropertyDescriptors(obj))
// {
//   foo: {
//     get: [Function: get foo],
//     set: undefined,
//     enumerable: true,
//     configurable: true
//   }
// }
// 创建带有getter/setter的对象副本
const clone = Object.defineProperties({}, Object.getOwnPropertyDescriptors(obj))

字符串方法

1. includes/startsWith/endsWith

const str = 'Hello world'
// includes
console.log(str.includes('world')) // true
console.log(str.includes('World')) // false
// startsWith
console.log(str.startsWith('Hello')) // true
console.log(str.startsWith('hello')) // false
// endsWith
console.log(str.endsWith('world')) // true
console.log(str.endsWith('World')) // false

2. padStart/padEnd

// 补全字符串长度
console.log('1'.padStart(3, '0')) // '001'
console.log('1'.padEnd(3, '0')) // '100'
// 常见应用:格式化日期
const month = '5'
const day = '3'
const formattedDate = `${month.padStart(2, '0')}/${day.padStart(2, '0')}` // "05/03"

3. repeat

// 重复字符串
console.log('ha'.repeat(3)) // 'hahaha'
// 实际应用:生成缩进
function indent(level) {
  return ' '.repeat(level * 2)
}

实际应用场景

1. 数据处理

// 数组去重
const unique = Array.from(new Set([1, 1, 2, 2, 3]))
// 数据转换
const prices = Object.entries(data).map(([key, value]) => ({
  item: key,
  price: value,
}))

2. 字符串处理

// 格式化显示
function formatNumber(num) {
  return String(num).padStart(6, '0')
}
// 检查文件类型
function isImageFile(filename) {
  return filename.toLowerCase().endsWith('.jpg') || filename.toLowerCase().endsWith('.png')
}

3. 对象操作

// 配置合并
const defaultConfig = { timeout: 1000, retry: 3 }
const userConfig = { timeout: 2000 }
const config = Object.assign({}, defaultConfig, userConfig)

最佳实践

数组方法使用建议

对象方法使用建议

字符串方法使用建议

Array.from 和扩展运算符的区别是什么?

参考答案:Array.from 和扩展运算符(…)都可以将类数组对象或可迭代对象转换为数组,但有以下区别:

Object.assign 实现深拷贝需要注意什么?

参考答案:Object.assign 本身只实现浅拷贝,要实现深拷贝需注意:

如何判断一个值在数组中的存在?includes 和 indexOf 的区别?

参考答案:判断值是否在数组中存在的方法有:

主要区别:

flat 和 flatMap 的使用场景是什么?

参考答案:

Object.entries 的实际应用有哪些?

参考答案:Object.entries 的实际应用包括:

新增的字符串方法有什么优势?

参考答案:ES6 新增字符串方法的优势:

如何选择合适的 API 方法?

参考答案:选择合适的 API 方法应考虑:

到此这篇关于ES6 新增 API 方法的文章就介绍到这了,更多相关ES6 新增 API 方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文