js基本功五
目录
js基本功(五)
rest参数
Rest参数是ES6引入的一个特性,用于将函数调用时传递的不定数量的参数收集到一个数组中。
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 输出 15
在上述代码中,…numbers会将所有传入的参数收集到一个名为numbers的数组中。Rest参数必须是函数参数列表中的最后一个参数。
arguments
arguments 是一个特殊的对象,用于在函数内部访问传递给该函数的所有参数。它是一个类数组对象,包含函数调用时传递的所有参数,但并不是一个真正的数组,因此它没有数组的内置方法(如 .map()、.forEach() 等)
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3, 4, 5)); // 输出 15
与 rest 参数的比较:
- arguments 是一个类数组对象,而 rest 参数是一个真正的数组。
- rest 参数需要显式声明,而 arguments 是函数内部自动提供的。
concat
concat对原数组不产生影响
const arr = [1,2]
const arr1 = [3,4]
const arr2 = arr.concat(arr1)
arr2// [1, 2, 3, 4]
arr // [1,2]
arr1 // [3,4]
浅拷贝
数组中的concat,slice,扩展运算符,对象中的Object.assign是浅拷贝
要用深拷贝就用JSON.stringify 将对象转为字符串,再使用 JSON.parse
flat
多维数组扁平化
const arr1 = [1, [2, [3, [4]]]];
console.log(arr1.flat()); // [1, 2, [3, [4]]]
console.log(arr1.flat(2)); // [1, 2, 3, [4]]
console.log(arr1.flat(Infinity)); // [1, 2, 3, 4]
flatMap
只能扁平化一层,不能像flat那样指定Infinity无限层级
扩展运算符
let{ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x// 1 y // 2 z // { a: 3, b: 4 }
注意这里跟rest参数对比一下,z并不是一个数组
为什么Symbol不能用new关键字
Symbol 是一种原始数据类型,而不是一个构造函数,因此不能使用 new 关键字来创建。