還是大劍師蘭特:曾是美國某知名大學(xué)計算機專業(yè)研究生,現(xiàn)為航空航海領(lǐng)域高級前端工程師;CSDN知名博主,GIS領(lǐng)域優(yōu)質(zhì)創(chuàng)作者,深耕openlayers、leaflet、mapbox、cesium,canvas,webgl,echarts等技術(shù)開發(fā),歡迎加底部微信(gis-dajianshi),一起交流。
No. | 內(nèi)容鏈接 |
---|---|
1 | Openlayers 【入門教程】 - 【源代碼+示例300+】 |
2 | Leaflet 【入門教程】 - 【源代碼+圖文示例 150+】 |
3 | Cesium 【入門教程】 - 【源代碼+圖文示例200+】 |
4 | MapboxGL【入門教程】 - 【源代碼+圖文示例150+】 |
5 | 前端就業(yè)寶典 【面試題+詳細答案 1000+】 |
文章來源:http://www.zghlxwxcb.cn/news/detail-849577.html
ES6 的解構(gòu)賦值(Destructuring Assignment)是一種新的聲明和提取數(shù)組或?qū)ο髮傩缘暮啙嵎绞?,它允許我們從數(shù)組或?qū)ο笾刑崛≈挡⑦@些值賦給相應(yīng)的變量。這種方式簡化了變量賦值和參數(shù)傳遞的過程,提高了代碼的可讀性和便利性。文章來源地址http://www.zghlxwxcb.cn/news/detail-849577.html
一、 數(shù)組解構(gòu)賦值
示例代碼:
// 從數(shù)組中解構(gòu)賦值
let [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 輸出:1 2 3
// 默認(rèn)值
let [x = 'default', y = 'fallback'] = [1];
console.log(x, y); // 輸出:1 fallback
// 解構(gòu)剩余部分
let [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 輸出:1
console.log(rest); // 輸出:[2, 3, 4, 5]
// 解構(gòu)嵌套數(shù)組
let [head, [nested1, nested2]] = [1, [2, 3]];
console.log(head, nested1, nested2); // 輸出:1 2 3
二、對象解構(gòu)賦值
示例代碼:
// 從對象中解構(gòu)賦值
let { firstName: fn, lastName: ln } = { firstName: 'Alice', lastName: 'Smith' };
console.log(fn, ln); // 輸出:Alice Smith
// 如果對象沒有該屬性,可以通過默認(rèn)值賦值
let { color = 'red' } = {};
console.log(color); // 輸出:red
// 直接解構(gòu)賦值給同名變量
let { firstName, lastName } = { firstName: 'Bob', lastName: 'Johnson' };
console.log(firstName, lastName); // 輸出:Bob Johnson
// 解構(gòu)嵌套對象
let obj = { profile: { name: 'Tom', age: 25 } };
let { profile: { name, age } } = obj;
console.log(name, age); // 輸出:Tom 25
// 非必須存在的屬性,可以放在單獨的圓括號中
let { a, b, c } = { a: 1, b: 2 };
({ c } = { c: 3 }); // 不報錯,即使c不在原始對象中
console.log(a, b, c); // 輸出:1 2 3
三、應(yīng)用場景
- 交換兩個變量的值無需臨時變量:
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 輸出:2 1
- 函數(shù)參數(shù)的簡化:
function processOptions({ width = 800, height = 600, title }) {
// ...
}
processOptions({ title: 'My App', height: 400 });
- 函數(shù)返回多個值時的便捷處理:
function fetchInfo() {
return [1, 2, 3];
}
let [info1, info2, info3] = fetchInfo();
- 處理 JSON 數(shù)據(jù)或 API 回調(diào):
let jsonData = { id: 1, name: 'John Doe' };
let { id, name } = jsonData;
console.log(id, name); // 輸出:1 John Doe
到了這里,關(guān)于深入理解 ES6 的解構(gòu)表達式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!