JavaScript 中的解构

来源:undefined 2025-01-21 03:52:40 1031

JavaScript 解构:示例与练习

本文提供 javascript 解构的示例和练习,帮助您更好地理解和应用解构技术。

嵌套解构:

从嵌套对象中提取值:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

const person = {

name: john,

address: {

city: new york,

country: usa

}

};

let {

name,

address: { city, country }

} = person;

console.log(name, city, country); // 输出: john new york usa

登录后复制

数组解构:

从数组中提取值并赋值给变量:

立即学习Java免费学习笔记(深入)”;

1

2

3

const numbers = [1, 2, 3];

let [a, b, c] = numbers;

console.log(a, b, c); // 输出: 1 2 3

登录后复制

练习 1:日期字符串分割

编写一个函数,接收 dd/mm/yyyy 格式的日期字符串,并返回一个包含日、月、年的数组。

1

2

3

4

5

6

function splitDate(dateString) {

return dateString.split(/);

}

let [day, month, year] = splitDate(11/05/2005);

console.log(day, month, year); // 输出: 11 05 2005

登录后复制

练习 2:改进日期分割函数

使用解构改进练习 1 中的函数,直接返回日、月、年三个变量。

1

2

3

4

5

6

7

function splitDateImproved(dateString) {

const [day, month, year] = dateString.split(/);

return {day, month, year};

}

const {day, month, year} = splitDateImproved(20/05/2024);

console.log(day, month, year); // 输出: 20 05 2024

登录后复制

函数参数解构:

使用解构简化函数参数:

1

2

3

4

5

6

7

8

9

10

11

function printPerson({ name, age, city }) {

console.log(name, age, city);

}

const person = {

name: john,

age: 30,

city: new york

};

printPerson(person); // 输出: john 30 new york

登录后复制

使用自定义变量名进行解构:

1

2

3

4

5

function printPerson2({ name: n, age: a, city: c }) {

console.log(n, a, c);

}

printPerson2(person); // 输出: john 30 new york

登录后复制

数组解构作为函数参数:

使用数组解构作为函数参数:

1

2

3

4

5

6

function printPerson3([name, age, city]) {

console.log(name, age, city);

}

const personArray = [Jooaca, 30, New York];

printPerson3(personArray); // 输出: Jooaca 30 New York

登录后复制

希望这些示例和练习能够帮助您理解和掌握 JavaScript 解构。 记住,解构可以使您的代码更简洁、更易于阅读和维护。

以上就是JavaScript 中的解构的详细内容,更多请关注php中文网其它相关文章!

最新文章