前言
最近在处理公司字体面板这一块的内容,开发过程中遇到了很多数组相关的API,很多API都不是很熟悉就想总结一下这部分,如果喜欢的话可以点波赞/关注,支持一下,或者收藏起来之后遇到可以查询,希望大家看完本文可以有所收获。
一、增
1.push
- 定义:往数组后面新增元素
- 返回值:无
- 参数:一个或多个元素
const colors = []; colors.push('green', 'red');
console.log(colors); // ['green', 'red']
2.unshift
- 定义:往数组前面新增元素
- 返回值:无
- 参数:一个或多个元素
const colors = ['red'];
colors.unshift('blue', 'grey');
console.log(colors); // ['blue', 'grey', 'red']
3.使用 length 属性追加元素
var arr = [1, 2, 3, 4, 5];
arr[length] = 6;
console.log(arr); // [1, 2, 3, 4, 5, 6];
4.splice
- 定义:往数组前面新增、插入、删除元素
- 返回值:无
- 参数:
- splice(position, count) 表示从 position 索引的位置开始,删除count个元素
- splice(position, 0, a, b, ...) 表示从 position 索引的元素后面插入一系列的元素
- splice(postion, count, a, b, ...) 表示从 position 索引的位置开始,删除 count 个元素,然后再插入一系列的元素
var arr = [1, 2, 3, 4, 5];
arr.splice(5, 0, 6);
console.log(arr); // [1, 2, 3, 4, 5, 6];
5.使用扩展运算符新增
var arr = [1, 2, 3, 4, 5]
arr = [...arr, 6]
console.log(arr); // [1, 2, 3, 4, 5, 6]
6.concat合并数组
- 定义:用于将一个或多个数组或值合并至一个数组中,该方法不会改变原数组
- 返回值:新数组
- 参数:值或者数组(可以传对象)
- 注意:
concat返回的是一个浅拷贝
//连接两个数组
const arr = [1, 2, 3].concat([4, 5])
console.log(arr) // [1,2,3,4,5]
//连接三个数组
const arr1 = [1, 2]
const arr2 = [3, 4]
const arr3 = [5, 6]
const arr4 = arr1.concat(arr2, arr3)
console.log(arr4) // [1, 2, 3, 4, 5, 6]
//连接值和数组
const arr1 = [1, 2]
const arr2 = 3
const arr3 = [5, 6]
const arr4 = arr1.concat(arr2, arr3)
console.log(arr4) // [1, 2, 3, 5, 6]
//连接对象
const arr1 = [1]
const arr2 = [3, 4]
const arr3 = {
a: 1,
b: 2
}
const arr4 = arr1.concat(arr2, arr3)
console.log(arr4) // [1, 3, 4, {a:1, b:2}]
二、删
1.pop
- 定义:方法用于删除并返回数组的最后一个元素。
- 返回值:删除的元素
- 参数:无
const color = ['green','red']
const item = colors.pop();
console.log(item); // 'red'
console.log(colors); // ['green']
2.shift
- 定义:方法用于删除并返回数组的开头一个元素。
- 返回值:删除的元素
- 参数:无
const colors = ['green', 'red'];
const item = colors.shift();
console.log(item); // 'green'
console.log(colors); // ['red']
3.splice
- 定义:往数组前面新增、插入、删除元素
- 返回值:无
- 参数:
- splice(position, count) 表示从 position 索引的位置开始,删除count个元素
- splice(position, 0, a, b, ...) 表示从 position 索引的元素后面插入一系列的元素
- splice(postion, count, a, b, ...) 表示从 position 索引的位置开始,删除 count 个元素,然后再插入一系列的元素
var arr = [1, 2, 3, 4, 5];
arr.splice(5, 0, 6);
console.log(arr); // [1, 2, 3, 4, 5, 6];
4.length删除最后一个元素
var arr = [1,2,3,4,5]
arr.length = arr.length - 1
// arr => [1,2,3,4]
三、改
1.通过索引
let arr = [1,2,3,4];
arr[0] = 1 // 1
2.通过splice
const arr = [1, 2, 3, 4, 5];
arr.splice(1, 1, 10)
console.log(arr); // [1, 10, 3, 4, 5]
四、查
1.includes()
- 定义:用来判断一个数组是否包含一个指定的值,如果包含则返回 true,否则返回 false。
- 返回值:boolean
- 参数:valueToFind,fromIndex(可选)
- 第一个参数是‘需要查找的元素值’,
- 第二个参数是‘从哪个索引处开始查找’,
- 第二个参数如果为负数,则会按升序从 array.length + fromIndex 的索引开始查找(负数就是从倒数第几个数开始找)。不会改变查找顺序
- 注意:如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。如果抵消后的索引值仍小于0,则整个数组都将会被查询。其默认值为0。
var a = [1,2,3,4,5,6]
a.includes(2) // true
a.includes(2,3) // false
a.includes(5,-2) // true
a.includes(5,-1) // false
2.indexOf()
- 定义:方法返回指定元素在数组中的第一个索引,如果不存在,则返回-1。
- 返回值:number
- 参数:两个参数searchElement,fromIndex (可选)
- 第一个参数是‘要查找的元素’
- 第二个参数是‘开始查找的索引位置’
- 如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回-1。
- 如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即-1表示从最后一个元素开始查找,-2表示从倒数第二个元素开始查找 ,以此类推。
- 注意:如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。如果抵消后的索引值仍小于0,则整个数组都将会被查询。其默认值为0。
var array = [2, 5, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
3.lastIndexOf()
- 定义:方法返回指定元素在数组中的最后一个的索引,如果不存在则返回 -1。
- 返回值:number
- 参数:两个参数searchElement,fromIndex (可选)
从数组的后面向前查找,从 fromIndex 处开始。
- 第一个参数是‘被查找的元素’。
- 第二个参数是‘从此位置开始逆向查找’,默认为数组的长度减 1(arr.length - 1),即整个数组都被查找。
- 如果该值大于或等于数组的长度,则整个数组会被查找。
- 如果为负值,将其视为从数组末尾向前的偏移。即使该值为负,数组仍然会被从后向前查找。
- 如果该值为负时,其绝对值大于数组长度,则方法返回 -1,即数组不会被查找。
var array = [2, 5, 9, 2];
array.lastIndexOf(2); // 3
array.lastIndexOf(7); // -1
array.lastIndexOf(2, 3); // 3
array.lastIndexOf(2, 2); // 0
array.lastIndexOf(2, -2); // 0
array.lastIndexOf(2, -1); // 3
4.some()
- 语法:
array.some(function(currentValue,index,arr),thisValue) - 定义:测试数组中是不是至少有1个元素通过了被提供的函数测试
- 返回值:boolean
- 参数:callback(currentValue,index,array),thisValue
- thisValue:可选,执行 callback 时使用的 this 值。
- elem 正在处理的元素
- index 可选 正在处理元素的index
- arr 可选,被遍历的数组本身。
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
还可以使用箭头函数实现相同的效果。
[2, 5, 8, 1, 4].some(x => x > 10); // false
[12, 5, 8, 1, 4].some(x => x > 10); // true
5.every()
- 语法:
array.every(function(currentValue,index,arr),thisValue) - 定义:测试一个数组内的所有元素是否都能通过某个指定函数的测试
- 返回值:boolean
- 参数:callback(currentValue,index,array),thisValue
- thisValue:可选,执行 callback 时使用的 this 值。
- elem 正在处理的元素
- index 可选 正在处理元素的index
- arr 可选,被遍历的数组本身。 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
6.filter()
- 语法:
array.filter(function(currentValue,index,arr),thisValue) - 定义:创建一个新数组, 包含通过所提供函数实现的测试的所有元素。
- 返回值:array
- 参数:callback(elem,index,array),thisValue
- callback 用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。
function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 35].filter(isBigEnough);
// filtered is [12, 130, 35]
7.find()
- 语法:
array.find(function(currentValue,index,arr),thisValue) - 定义:方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
- 返回值:数组元素 | undefined
- 参数:callback(elem,index,array),thisValue
- 用对象的属性查找数组里的对象。
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'orange', quantity: 5}
];
function findOranges(fruit) {
return fruit.name === 'orange';
}
console.log(inventory.find(findOrange));
// { name: 'orange', quantity: 5 }
8.findIndex()
- 语法:
array.findIndex(function(currentValue,index,arr),thisValue) - 定义:方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
- 返回值:number
- 参数:callback(currentValue,index,array),thisValue
- 用对象的属性查找数组里的对象。
/*对象,取出满足要求的下标*/
const nameArr=[
{id:1,userName:"a",age:16},
{id:2,userName:"b",age:18},
{id:3,userName:"c",age:26 },
{id:4,userName:"d",age:18}
];
/*满足条件,返回下标位置1*/
var i1=nameArr.findIndex((value)=>value.age==18);
console.log(i1);
/*没有满足条件的,返回-1*/
var i2=nameArr.findIndex((value)=>value.age==168);
console.log(i2);
五、遍历
1.for
可以使用临时变量,将长度缓存起来,避免重复获取数组长度,当数组较大时优化效果才会比较明显。
/ arr 是要遍历的数组
// arr[i] 是遍历的数组的元素
// i 是数组的元素对应的下标(索引号)
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
let arr = [1, 2, 3, 4];
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i] + 1; // 直接通过索引修改原数组的值
}
console.log(arr); // [2,3,4,5]
let list = [{sex: '男'},{sex: '女'},{sex: '男'}];
for (let i = 0; i < list.length; i++) {
list[i].sex = '女';
}
console.log(list); // [{sex: '女'}, {sex: '女'}, {sex: '女'}]
2.for of遍历,获取值
// arr 遍历的数组
// item 遍历的数组的元素
for(var item of arr) {
console.log(item);
}
let arr = [1, 2, 3, 4];
for(var item of arr) {
console.log(item);
}
3.for in遍历,获取索引
let arr = [1, 2, 3, 4, 5]
Array.prototype.id = 123
arr.name = 'Jessica'
for (let index in arr) {
if (index == 2) {
// break;//0,1
// continue;//0,1,3,4
// return;//0,1
}
console.log(index, arr[index]);//遍历[1,2,3,4,5,Jessica,123]
}
4.以上2、3的区别
两者区别:
- 1.for-in只是获取数组的索引;而for-of会获取数组的值
- 2.for-in会遍历对象的整个原型链,性能差;
- 3.而for-of只遍历当前对象,不会遍历原型链
- 4.对于数组的遍历,for-in会返回数组中所有可枚举的属性(包括原型链上可枚举的属性);for-of只返回数组的下标对应的属性值
- 5.for-of适用遍历数组/字符串/map/set等有迭代器对象的集合,但是不能遍历普通对象(obj is not iterable)
5.forEach()
- 语法:
array.forEach(function(currentValue,index,curArr),thisValue) - 定义:用于调用数组的每个元素,并将元素传递给回调函数,没有返回值,原数组不变。
- 返回值:无
- 参数:callback(currentValue,index,curArr),thisValue
- 注意:forEach() 对于空数组是不会执行回调函数的。
// arrObj 需要遍历的数组
// item 遍历出的每一个元素
// index 元素对应的下标
// curArr 数组本身
// 无返回值
arrObj.forEach(function(item,index,curArr) {
console.log(item);
});
let arr = [1, 2, 3, 4];
arr.forEach(item => {
item = item * 2;
});
console.log(arr); // [1, 2, 3, 4] 原数组保持不变
6.map()
- 语法:
array.map(function(currentValue,index,curArr),thisValue) - 定义:按照原始数组元素顺序依次处理元素。
- 返回值:方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值,并没有改变原来的数组。
- 参数:callback(currentValue,index,curArr),thisValue
- 注意:map() 不会对空数组进行检测。
// arrObj 需要遍历的数组
// item 遍历出的每一个元素
// index 元素对应的下标
// curArr 数组本身
// 有返回值
// newArr 新返回的数组
// 数组元素个数不变,但是按照一定的条件转换
arrObj.map(function(item,index,curArr) {
return item*2;
});
let arr = [1, 2, 3, 4];
let newArr = arr.map(item => {
return item * 2;
});
console.log(arr); // [1, 2, 3, 4] 原数组保持不变
console.log(newArr); // [2, 4, 6, 8] 返回新数组
7.filter()
- 语法:
array.filter(function(currentValue,index,curArr),thisValue) - 定义:将所有元素进行判断,将满足条件的元素作为一个新的数组返回, 原数组不变。
- 返回值:满足条件的元素作为一个新的数组,并没有改变原来的数组。
- 参数:callback(currentValue,index,curArr),thisValue
- 注意:filter() 不会对空数组进行检测。
// arrObj 需要遍历的数组
// item 遍历出的每一个元素
// index 元素对应的下标
// curArr 数组本身
// 有返回值,返回满足某个条件的元素构成的数组
// 数组元素个数可能改变,按照一定的条件返回
arrObj.filter(function(item,index,curArr) {
return item < 3;
});
let arr = [1, 2, 3, 4];
let newArr = arr.filter(item => {
return item < 3;
});
console.log(arr); // [1, 2, 3, 4] 原数组保持不变
console.log(newArr); // [1, 2] 返回新数组
8.find()
- 语法:
array.find(function(currentValue,index,curArr),thisValue) - 定义:查找数组中符合条件的元素,当数组中的元素在测试条件时返回true,find()返回符合条件的元素,之后的值不会再执行函数;如果没有符合条件的元素则返回undefined,原数组不变。
- 返回值:满足条件的元素,find()返回符合条件的元素,之后的值不会再执行函数;如果没有符合条件的元素则返回undefined,原数组不变。
- 参数:callback(currentValue,index,curArr),thisValue
- 注意:find() 对于空数组,函数是不会执行的。
let arr = [1, 2, 3, 4];
let newArr1 = arr.find(item => {
return item > 2;
});
let newArr2 = arr.find(item => {
return item > 5;
});
console.log(arr); // [1, 2, 3, 4] 原数组保持不变
console.log(newArr1); // 3 返回第一个符合条件的元素
console.log(newArr2); // undefined 没有符合条件的元素则返回undefined
9.findIndex()
- 语法:
array.findIndex(function(currentValue,index,curArr),thisValue) - 定义:方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
- 返回值:number
- 参数:callback(currentValue,index,curArr),thisValue
- 用对象的属性查找数组里的对象。
/*对象,取出满足要求的下标*/
const nameArr=[
{id:1,userName:"a",age:16},
{id:2,userName:"b",age:18},
{id:3,userName:"c",age:26 },
{id:4,userName:"d",age:18}
];
/*满足条件,返回下标位置1*/
var i1=nameArr.findIndex((value)=>value.age==18);
console.log(i1);
/*没有满足条件的,返回-1*/
var i2=nameArr.findIndex((value)=>value.age==168);
console.log(i2);
10.indexOf()
- 定义:方法返回指定元素在数组中的第一个索引,如果不存在,则返回-1。
- 返回值:number
- 参数:两个参数searchElement,fromIndex (可选)
- 第一个参数是‘要查找的元素’
- 第二个参数是‘开始查找的索引位置’
- 如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回-1。
- 如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即-1表示从最后一个元素开始查找,-2表示从倒数第二个元素开始查找 ,以此类推。
- 注意:如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。如果抵消后的索引值仍小于0,则整个数组都将会被查询。其默认值为0。
var array = [2, 5, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
11.lastIndexOf()
- 定义:方法返回指定元素在数组中的最后一个的索引,如果不存在则返回 -1。
- 返回值:number
- 参数:两个参数searchElement,fromIndex (可选)
从数组的后面向前查找,从 fromIndex 处开始。
- 第一个参数是‘被查找的元素’。
- 第二个参数是‘从此位置开始逆向查找’,默认为数组的长度减 1(arr.length - 1),即整个数组都被查找。
- 如果该值大于或等于数组的长度,则整个数组会被查找。
- 如果为负值,将其视为从数组末尾向前的偏移。即使该值为负,数组仍然会被从后向前查找。
- 如果该值为负时,其绝对值大于数组长度,则方法返回 -1,即数组不会被查找。
var array = [2, 5, 9, 2];
array.lastIndexOf(2); // 3
array.lastIndexOf(7); // -1
array.lastIndexOf(2, 3); // 3
array.lastIndexOf(2, 2); // 0
array.lastIndexOf(2, -2); // 0
array.lastIndexOf(2, -1); // 3
12.some()
- 语法:
array.some(function(currentValue,index,arr),thisValue) - 定义:测试数组中是不是至少有1个元素通过了被提供的函数测试
- 返回值:boolean
- 参数:callback(currentValue,index,array),thisValue
- thisValue:可选,执行 callback 时使用的 this 值。
- elem 正在处理的元素
- index 可选 正在处理元素的index
- arr 可选,被遍历的数组本身。
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
还可以使用箭头函数实现相同的效果。
[2, 5, 8, 1, 4].some(x => x > 10); // false
[12, 5, 8, 1, 4].some(x => x > 10); // true
13.every()
- 语法:
array.every(function(currentValue,index,arr),thisValue) - 定义:测试一个数组内的所有元素是否都能通过某个指定函数的测试
- 返回值:boolean
- 参数:callback(currentValue,index,array),thisValue
- thisValue:可选,执行 callback 时使用的 this 值。
- elem 正在处理的元素
- index 可选 正在处理元素的index
- arr 可选,被遍历的数组本身。 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
14.reduce累加器
- 语法:
array.reduce(function(pre, currentValue, currentIndex, arr), initialValue) - 定义:测试一个数组内的所有元素是否都能通过某个指定函数的测试
- 返回值:boolean
- 参数:两个参数
- 第一个为回调函数
- 初始值或计算结束后的返回值
- 当前元素
- 当前元素的索引
- 当前元素所属的数组对象
- 第二个为初始赋值
- 初始值,非必传
- 第一个为回调函数
- 注意:如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。如果提供initialValue,从索引0开始。
//未赋初始值
//index是从1开始的,第一次的prev的值是数组的第一个值。数组长度是4,循环3次。
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (prev, cur, index, arr) {
console.log(prev, cur, index);
return prev + cur;
});
console.log(arr, sum);
//打印结果
1 2 1
3 3 2
6 4 3
[ 1, 2, 3, 4 ] 10
//赋初始值
这个例子index是从0开始的,第一次的prev的值是我们设置的初始值0,数组长度是4,reduce函数循环4次。
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (prev, cur, index, arr) {
console.log(prev, cur, index);
return prev + cur;
}, 0);
console.log(arr, sum);
//打印结果
0 1 0
1 2 1
3 3 2
6 4 3
[ 1, 2, 3, 4 ] 10
15.reduceRight()
- 语法:
array.reduceRight(function(pre, currentValue, currentIndex, arr), initialValue) - 定义:数组中的每个值(从右到左)开始缩减,最终为一个值。
- 返回值:boolean
- 参数:两个参数
- 第一个为回调函数
- 初始值或计算结束后的返回值
- 当前元素
- 当前元素的索引
- 当前元素所属的数组对象
- 第二个为初始赋值
- 初始值,非必传
- 第一个为回调函数
- 注意:如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。如果提供initialValue,从索引0开始。
let arrNum = [2, 4, 6, 8, 10];
// 累加
let sum = arrNum.reduceRight(function(x, y){
return x + y;
});
console.log(sum); // 30
// 累乘
let multiple = arrNum.reduceRight(function(x, y){
return x * y;
});
console.log(multiple); // 3840
// 求最大值
let bigger = arrNum.reduceRight(function(x, y){
return x > y ? x : y;
});
console.log(bigger); // 10
16.遍历器
截止到ES6,JavaScript 已经拥有了数组、对象、Map集合和Set集合这样四种数据结构。
为了统一和简化遍历这四种数据结构的操作,ES6引入了遍历器机制。
ES6 规定,可遍历的对象都具有Symbol.iterator 属性,这个属性指向一个函数,就是当前对象默认的遍历器生成函数。
这个遍历器生成函数大致的模样可以用ES5 语法模拟出来:这个函数返回一个next() 方法,每调用next() 方法,都会返回数据结构的当前成员的信息。
具体来说,就是返回一个包含value和done两个属性的对象。
其中,value属性是当前成员的值,done属性是一个布尔值,表示遍历是否结束。
在ES6 中,已经默认为绝大多数內建的数据结构提供了遍历器,不需要自己去创建。
// keys()方法:默认遍历器,其值为集合中的所有键名。
// values()方法:默认遍历器,其值为集合中的所有值。
// entries()方法:默认遍历器,其值为所有成员的键值对。
const arr = ["A", "B", "C"];
console.log([...arr.keys()]); // [0, 1, 2]
console.log([...arr.values()]); // ["A", "B", "C"]
console.log([...arr.entries()]); // [[0, "A"],[1, "B"],[2, "C"]]
const set = new Set(arr);
console.log([...set.keys()]); // ["A", "B", "C"]
console.log([...set.values()]); // ["A", "B", "C"]
console.log([...set.entries()]); // [["A", "A"],["B", "B"],["C", "C"]]
const map = new Map().set("name", "Tom").set("age", 19);
console.log([...map.keys()]); // ["name", "age"]
console.log([...map.values()]); // ["Tom", 19]
console.log([...map.entries()]); // [["name", "Tom"],["age", 19]]
每个数据结构都有一个默认的遍历器,例如数组的默认遍历器是values(),在没有明确指定遍历器的情况下,这些数据结构都会使用默认的遍历器。
const arr = ["A", "B", "C"];
console.log(typeof arr[Symbol.iterator] === "function"); // true
console.log(arr[Symbol.iterator]); // function values() { ... }
const set = new Set(arr);
console.log(typeof set[Symbol.iterator] === "function"); // true
console.log(set[Symbol.iterator]); // function values() { ... }
const map = new Map().set("name", "Tom").set("age", 19);
console.log(typeof map[Symbol.iterator] === "function"); // true
console.log(map[Symbol.iterator]); // function entries() { ... }
原生具备遍历器的对象:
数组、Map集合、Set集合、字符串、arguments和 NodeList(节点列表)。
对象(Object)默认是不可遍历的,我们可以通过Object.keys()、Object.values()和Object.entries() 方法把对象变成数组,使其拥有遍历器;或者直接为对象添加Symbol.iterator 属性来自定义遍历器。
const obj = {
name: "Tom",
age: 19
}
console.log(typeof Object.entries(obj)[Symbol.iterator] === "function"); // true
console.log([...Object.entries(obj)]); // [["name", "Tom"],["age", 19]]
六、创建
1.字面量方法
var a = [1, 2, 3]; // [1,2,3];
2.构造器方式
// 实际上 new Array === Array,加不加new 一点影响都没有。
var a = Array(); // []
var a = Array(3); // [,,]
var a = Array(1, 2, 3); // [ 1, 2, 3 ]
避免使用这种方式,因为参数不同,行为有差异
3.Array.of()
- 定义:返回由所有参数值组成的数组,如果没有参数,就返回一个空数组。
- 返回值:参数组成的数组
- 目的:Array.of() 出现的目的是为了解决上述构造器因参数个数不同,导致的行为有差异的问题。
4.Arrary.from()
-
定义:用于将两类对象转为真正的数组(不改变原对象,返回新的数组)。
-
返回值:数组
-
参数:
- 第一个参数(必需):要转化为真正数组的对象。
- 第二个参数(可选): 类似数组的map方法,对每个元素进行处理,将处理后的值放入返回的数组。
- 第三个参数(可选): 用来绑定this。
// 1. 对象拥有length属性
let obj = {0: 'a', 1: 'b', 2:'c', length: 3};
let arr = Array.from(obj); // ['a','b','c'];
// 2. 部署了 Iterator接口的数据结构 比如:字符串、Set、NodeList对象
let arr = Array.from('hello'); // ['h','e','l','l','o']
let arr = Array.from(new Set(['a','b'])); // ['a','b']
七、其他方法
1.Array.fill()
- 语法:
array.fill(value, start, end) - 定义:方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。
- 返回值:修改后的数组
- 参数:
- value | 必需。填充的值。 | | ------- | ------------------------------ | | start | 可选。开始填充位置。 | | end | 可选。停止填充位置 (默认为 array.length)
[1, 2, 3].fill(4); // [4, 4, 4]
[1, 2, 3].fill(4, 1); // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2); // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3); // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2); // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5); // [1, 2, 3]
Array(3).fill(4); // [4, 4, 4] 创建长度为几,值都相同的数组
[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}
2.Array.slice()切片
- 语法:
Array.slice(start,end) - 定义:通过索引位置获取新的数组,该方法不会修改原数组,只是返回一个新的子数组。
- 返回值:新数组,不包括终止索引。
- 参数:
- Array - 原始数组;
- start - 必填;设定新数组的起始位置;如果是负数,则表示从数组尾部开始算起(-1指最后一个元素,-2 指倒数第二个元素,以此类推)。
- end - 可选;设定新数组的结束位置;如果不填写该参数,默认到数组结尾;如果是负数,则表示从数组尾部开始算起(-1 指最后一个元素,-2指倒数第二个元素,以此类推)。
//获取仅包含最后一个元素的子数组
var arr=[1,2,3,4,5];
arr.slice(-1);//[5]
//获取不包含最后一个元素的子数组
var arr=[1,2,3,4,5];
arr.slice(0, -1);//[1,2,3,4]
//从第二个元素开始的所有元素的子数组
var arr=[1,2,3,4,5];
arr.slice(1);//[2,3,4,5]
3.Array.join()
- 语法:
array.join(separator) - 定义:join() 方法用于把数组中的所有元素转换一个字符串。元素是通过指定的分隔符进行分隔的。
- 返回值:string该字符串是通过把 array 的每个元素转换为字符串,然后把这些字符串连接起来,在两个元素之间插入 separator 字符串而生成的。
- 参数:分隔符,默认为,
var arr = ["a","b","c"];
array = arr.join(undefined);
console.log(array);//a,b,c
array = arr.join("|");
console.log(array);//a|b|c
4.Array.reverse()
- 语法:
array.join(separator) - 定义:数组反转
- 返回值:颠倒顺序的数组
- 参数:无
const list = [1, 2, 3, 4, 5];
list.reverse(); ``// [5, 4, 3, 2, 1]
5.Array.sort()
-
语法:
arr.sort([compareFunction(a, b)]) -
定义:sort() 方法用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的。
-
返回值:排序后的数组
-
参数:用来指定按某种顺序进行排列的函数。如果省略,元素按照转换后的字符串的各字符的Unicode位点进行排序。
a:第一个用于比较的元素b:第二个用于比较的元素 如果指明了比较函数,那么数组按照调用该函数的返回值进行排序。
-
如果
compareFunction(a,b)小于0,那么a排b前面 -
如果
compareFunction(a,b)大于0,那么a排b后面 -
如果
compareFunction(a,b)等于0,那么a,b的相对位置不变
//升序
arr.sort((a, b) => {
return a - b
})
//降序
arr.sort((a, b) => {
return b - a
})
6.Array.isArray()
- 语法:
Array.isArray(obj) - 定义:isArray() 方法用于判断一个对象是否为数组。
- 返回值:如果对象是数组返回 true,否则返回 false。
- 参数:必需,要判断的对象。
var a = [1,2,3];
console.log(typeof a); //返回“object”
console.log(Array.isArray(a)); //true
//typeof 运算符只能显示数组的类型是 Object,
//Array.isArray() 方法可以直接返回布尔值。在条件表达式中,使用该方法非常实用。
7.Array.at
- 语法:
Array.at(index) - 定义:at() 方法访问数组元素,接收一个整数值并返回该索引的项目,允许正数和负数。负整数从数组中的最后一个项目开始倒数。
- 返回值:数组中的元素
- 参数:必需,索引
- 如果
index参数是一个正整数>= 0,该方法返回该索引处的项目。 - 如果
index参数大于或等于数组长度,则与常规访问器一样,该方法返回undefined:
const vegetables = ['a', 'b', 'c'];
vegetables.at(0); // => 'a'
vegetables.at(1); // => 'b'
vegetables.at(2); // => 'c'
vegetables.at(3); // => undefined
vegetables.at(-1); // => 'c'
vegetables.at(-2); // => 'b'
vegetables.at(-3); // => 'a'
vegetables.at(-4); // => undefined