ES6 新增 API 方法示例詳解
ES6 新增 API 方法
背景介紹
ECMAScript 6(簡稱 ES6)于 2015 年發(fā)布,帶來了 JavaScript 語言的重大更新。ES6 引入了眾多新特性和 API 方法,使 JavaScript 代碼更加簡潔、高效和易于維護。這些新增 API 極大地簡化了開發(fā)流程,提高了代碼質(zhì)量,成為現(xiàn)代 JavaScript 開發(fā)的基礎(chǔ)。
數(shù)組方法
1. Array.from()
// 類數(shù)組轉(zhuǎn)數(shù)組
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轉(zhuǎn)數(shù)組
const set = new Set(['a', 'b', 'c'])
const arrFromSet = Array.from(set)
console.log(arrFromSet) // ['a', 'b', 'c']2. Array.of()
// 創(chuàng)建數(shù)組 const arr1 = Array.of(7) console.log(arr1) // [7] const arr2 = Array.of(1, 2, 3) console.log(arr2) // [1, 2, 3] // 對比Array構(gòu)造函數(shù) 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]]
// 實際應(yīng)用
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
// }
// }
// 創(chuàng)建帶有g(shù)etter/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')) // false2. padStart/padEnd
// 補全字符串長度
console.log('1'.padStart(3, '0')) // '001'
console.log('1'.padEnd(3, '0')) // '100'
// 常見應(yīng)用:格式化日期
const month = '5'
const day = '3'
const formattedDate = `${month.padStart(2, '0')}/${day.padStart(2, '0')}` // "05/03"3. repeat
// 重復(fù)字符串
console.log('ha'.repeat(3)) // 'hahaha'
// 實際應(yīng)用:生成縮進
function indent(level) {
return ' '.repeat(level * 2)
}實際應(yīng)用場景
1. 數(shù)據(jù)處理
// 數(shù)組去重
const unique = Array.from(new Set([1, 1, 2, 2, 3]))
// 數(shù)據(jù)轉(zhuǎn)換
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)最佳實踐
數(shù)組方法使用建議
- 優(yōu)先使用新方法代替?zhèn)鹘y(tǒng)實現(xiàn)
- 注意方法的返回值和副作用
- 合理使用鏈?zhǔn)秸{(diào)用
對象方法使用建議
- 使用 Object.assign 進行淺拷貝
- 使用 entries 進行對象遍歷
- 注意屬性描述符的處理
字符串方法使用建議
- 使用新方法提高代碼可讀性
- 注意大小寫敏感性
- 合理使用字符串填充功能
Array.from 和擴展運算符的區(qū)別是什么?
參考答案:Array.from 和擴展運算符(…)都可以將類數(shù)組對象或可迭代對象轉(zhuǎn)換為數(shù)組,但有以下區(qū)別:
- Array.from 可以接受第二個參數(shù)(映射函數(shù)),類似于 map 功能
- Array.from 能處理的范圍更廣,可以處理有 length 屬性的普通對象
- 擴展運算符只能處理可迭代對象(實現(xiàn)了 Iterator 接口)
- 性能上,一般來說擴展運算符在處理可迭代對象時略快
Object.assign 實現(xiàn)深拷貝需要注意什么?
參考答案:Object.assign 本身只實現(xiàn)淺拷貝,要實現(xiàn)深拷貝需注意:
- Object.assign 只會復(fù)制屬性值,如果屬性是對象引用,只會復(fù)制引用而非對象本身
- 要實現(xiàn)深拷貝,可以遞歸處理嵌套對象
- 可以使用 JSON.parse(JSON.stringify(obj)) 簡單實現(xiàn)深拷貝,但這種方法不能處理函數(shù)、循環(huán)引用、特殊對象(如 Date、RegExp)等
- 更復(fù)雜場景應(yīng)使用專門的深拷貝庫,如 lodash 的_.cloneDeep()方法
如何判斷一個值在數(shù)組中的存在?includes 和 indexOf 的區(qū)別?
參考答案:判斷值是否在數(shù)組中存在的方法有:
- includes:返回布爾值,能正確處理 NaN
- indexOf:返回索引或-1,不能處理 NaN
- some:可以用自定義條件判斷
主要區(qū)別:
- includes 語義更清晰,直接返回 true/false
- includes 可以查找 NaN,而 indexOf 不能
- indexOf 可以精確知道元素位置,includes 不能
- 對于大型數(shù)組,性能基本相當(dāng)
flat 和 flatMap 的使用場景是什么?
參考答案:
flat 適用于:
- 扁平化嵌套數(shù)組結(jié)構(gòu)
- 清理數(shù)組中的空項(holes)
- 可以指定扁平化深度
flatMap 適用于:
- 處理需要先映射(map)再扁平化的場景
- 文本處理,如分詞、過濾空值
- 替代常見的 map 后 flat 的鏈?zhǔn)秸{(diào)用,提高性能
- 生成一對多的數(shù)據(jù)映射
Object.entries 的實際應(yīng)用有哪些?
參考答案:Object.entries 的實際應(yīng)用包括:
- 遍歷對象鍵值,比 Object.keys 更直接
- 將對象轉(zhuǎn)換為 Map:
new Map(Object.entries(obj)) - 對象的序列化和轉(zhuǎn)換
- 實現(xiàn)對象的過濾和轉(zhuǎn)換,如創(chuàng)建新對象時篩選特定屬性
- 對象排序:先轉(zhuǎn) entries,排序后再轉(zhuǎn)回對象
新增的字符串方法有什么優(yōu)勢?
參考答案:ES6 新增字符串方法的優(yōu)勢:
- 語義化更強:如 includes 比 indexOf 返回-1 更直觀
- 功能更專一:startsWith/endsWith 替代 indexOf+復(fù)雜判斷
- 簡化常見操作:padStart/padEnd 處理格式化,repeat 處理重復(fù)
- 提高代碼可讀性:減少了冗長的條件判斷和手動實現(xiàn)
- 性能優(yōu)化:原生方法通常比自定義實現(xiàn)更高效
如何選擇合適的 API 方法?
參考答案:選擇合適的 API 方法應(yīng)考慮:
- 功能需求:優(yōu)先選擇專為特定功能設(shè)計的 API
- 語義清晰度:選擇能表達(dá)代碼意圖的方法
- 瀏覽器兼容性:考慮目標(biāo)環(huán)境是否支持,是否需要 polyfill
- 性能因素:在性能關(guān)鍵場景,選擇最優(yōu)性能的方法
- 代碼一致性:保持項目中 API 使用的一致風(fēng)格
- 團隊熟悉度:考慮團隊對 API 的理解程度
到此這篇關(guān)于ES6 新增 API 方法的文章就介紹到這了,更多相關(guān)ES6 新增 API 方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于js new Date() 出現(xiàn)NaN 的分析
在一個項目中需要進行日期的格式化,后臺傳到前端是時間的整數(shù)(Date.getTime),當(dāng)后臺數(shù)據(jù)返回字符串時,發(fā)現(xiàn)轉(zhuǎn)換日期時在ie下變成NaN,但是真的是這樣嗎?接下來我們慢慢分析2012-10-10
JS實現(xiàn)將人民幣金額轉(zhuǎn)換為大寫的示例代碼
本篇文章主要是對使用JS實現(xiàn)將人民幣金額轉(zhuǎn)換為大寫的示例代碼進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-02-02
prototype.js簡單實現(xiàn)ajax功能示例
這篇文章主要介紹了prototype.js簡單實現(xiàn)ajax功能,結(jié)合實例形式分析了prototype.js前臺實現(xiàn)ajax與后臺struts的相關(guān)操作技巧,需要的朋友可以參考下2017-10-10
使用threejs實現(xiàn)第一人稱視角的移動的問題(示例代碼)
第一人稱視角的場景巡檢主要需要解決兩個問題,人物在場景中的移動和碰撞檢測。移動與碰撞功能是所有三維場景首先需要解決的基本問題,今天我們就通過最基本的threejs來完成第一人稱視角的場景巡檢功能,感興趣的朋友一起看看吧2022-02-02
使用ionic(選項卡欄tab) icon(圖標(biāo)) ionic上拉菜單(ActionSheet) 實現(xiàn)通訊錄界面切換實例
這篇文章主要介紹了使用ionic(選項卡欄tab) icon(圖標(biāo)) ionic上拉菜單(ActionSheet) 實現(xiàn)通訊錄界面切換實例代碼,需要的朋友可以參考下2017-10-10
JS函數(shù)內(nèi)部屬性之a(chǎn)rguments和this實例解析
在函數(shù)內(nèi)部,有兩個特殊的對象:arguments和this。這篇文章主要介紹了函數(shù)內(nèi)部屬性之a(chǎn)rguments和this ,需要的朋友可以參考下2018-10-10

