一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第5天,点击查看活动详情。
- 最近新学到的关于数组小知识点的总结,希望可以帮助到大家
一、数组的fill方法:
- 该方法用于使用固定值填充数组:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.fill("Runoob");
//["Runoob", "Runoob", "Runoob", "Runoob"];
二、Array.from()用法:
- 一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例
用法:
- 第一个参数是类数组、数组、或者可迭代对象。
- 第二个参数是可选参数:可以决定每个元素执行的回调;如果不传,默认返回当前元素
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]
可以实现的功能:
1. 可以实现数组去重并且合并:
function combine(){
let arr = [].concat.apply([], arguments); //没有去重复的新数组
return Array.from(new Set(arr));
}
var m = [1, 2, 2], n = [2,3,3];
console.log(combine(m,n)); //[1,2,3] 参数传一个实现去重
2. 生成数字范围:
function range(end) {
return Array.from({ length: end }, (_, index) => index);
}
range(4); // => [0, 1, 2, 3]
3. 使用固定值填充数组:
- 这里就用到了上面的fill方法,是Array.from方法和fill方法的结合
const length = 3;
const init = 0;
const result = Array.from({ length: 6 }).fill(init);
console.log(result) // => [0, 0, 0]
4. 克隆一个数组:此方法是浅拷贝,但是两个数组互相不相等
const numbers = [3, 6, 9];
const numbersCopy = Array.from(numbers);
numbers === numbersCopy; // => false
5. 将类数组转化成数组:
Array.from('Hey'); // => ['H', 'e', 'y']
三、解构赋值:
示例:
let obj = {
a: 1,
b: [1,2,3,4]
}
const {a, ...b} = obj //a = 1,b = {b: [1,2,3,4]}
const {a, b} = obj //a = 1,b = [1,2,3,4]
obj中没有该属性怎么赋默认值:
let obj = {
a: 1,
b: 2
}
const { a, b, c = "aaa" } = obj //a = 1,b =2, c = "aaa"
扩展运算符的作用:
1.可以代替apply方法:
- 不需要使用apply方法将数组转为函数的参数了。
- (如下所示,以后参数不能为数组的情况,可以直接使用扩展运算符传参数)
Math.max.apply(null,[14,3,77])
// ES6 的写法
Math.max(...[14,3,77])
// 等同于
Math.max(14,3,77);
2.可以实现数组的复制,修改新数组,不会影响旧数组。
let a = [1,2,3]
写法一:
let b = [...a]
写法二:
const [...b] = a; //b = [1,2,3]
3.合并数组:
- 但是是浅拷贝,如果数组里面是对象,修改了新数组d的值,旧数组也会受影响。
let a = [1,2,3]
let b = [4,5,6]
let c = [7,8,9]
写法1: let d = [...a, ...b, ...c]
写法2: const [...d] = [...a, ...b, ...c]
4.与解构赋值相结合:生成数组。
- 如下例子,使用解构赋值后的值一定是一个数组,且只能放在最后一位,否则会报错。
const[first,...rest]=[1,2,3,4,5];
first // 1
rest // [2, 3, 4, 5]
const[first,...rest]=[];
first // undefined
rest // []
const[first,...rest]=["foo"];
first // "foo"
rest // []
5.扩展运算符还可以将字符串转为真正的数组:
const a = [...'hello'] //['h', 'e', 'l', 'l', 'o']