js 数组常用函数总结

目录

1、push

2、unshif

3、pop

4、shift

5、concat

6、slice

7、splice

8、join

9、indexOf

 10、lastIndexOf

 11、forEach

12、map

13、filter

14、reduce

15、sort

16、reverse

17、includes

18、some

19、every

 20、toString

21.、find

 22、findLast

23、 findIndex

24、findLastIndex

 25、fill

26、reduceRight

27、 at

28、 copyWithin

29、 flat

30、 flatMap

31、 Array.from

32、 Array.of()

33、Array.isArray()


1、push

功能:向数组末尾添加一个或多个元素,并返回数组的新长度

//1. 向数组末尾添加单个元素
const numbers = ["cat", "dog", "bird"];
const length = numbers.push( "pig");
console.log(numbers);  // ['cat', 'dog', 'bird', 'pig']
console.log(length);   // 4
//2、向数组末尾添加多个元素
const fruits = ['apple', 'banana'];
fruits.push('kiwi', 'orange');
console.log(fruits);  // ['apple', 'banana', 'kiwi', 'orange']

2、unshif

功能:向数组开头添加一个或多个元素,并返回数组的新长度

//1. 向数组开头添加单个元素
const numbers = ["cat", "dog", "bird"];
const length = numbers.unshift( "pig");
console.log(numbers);  // [ 'pig','cat', 'dog', 'bird']
console.log(length);   // 4
//1. 向数组开头添加多个元素
const fruits = ['banana', 'orange'];
fruits.unshift('apple', 'kiwi');
console.log(fruits);  // ['apple', 'kiwi', 'banana', 'orange']

3、pop

功能:删除数组的最后一个元素,并返回删除的元素

//删除数组的最后一个元素
const fruits = ['apple', 'banana', 'kiwi'];
const removedElement = fruits.pop();
console.log(fruits);          // ['apple', 'banana']
console.log(removedElement);  // 'kiwi'

4、shift

功能:删除数组的第一个元素,并返回删除的元素

//删除数组的第一个元素
const fruits = ['apple', 'banana', 'kiwi'];
const removedElement = fruits.shift();
console.log(fruits);          // ['banana', 'kiwi']
console.log(removedElement);  // 'apple'
//如果删除空数组,结果将返回undefined
const emptyArray = [];
const removedElement = emptyArray.shift();
console.log(emptyArray);     // []
console.log(removedElement);  // undefined

5、concat

功能:将两个或多个数组合并成一个新数组原数组不变

//1. 连接两个数组:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const concatenatedArray = array1.concat(array2);
console.log(concatenatedArray);  // [1, 2, 3, 4, 5, 6]
//2. 连接数组和值:
const array = [1, 2, 3];
const value = 4;
const concatenatedArray = array.concat(value);
console.log(concatenatedArray);  // [1, 2, 3, 4]
//3. 连接多个数组:
const array1 = [1, 2];
const array2 = [3, 4];
const array3 = [5, 6];
const concatenatedArray = array1.concat(array2, array3);
console.log(concatenatedArray);  // [1, 2, 3, 4, 5, 6]

6、slice

功能:从数组中提取指定范围的元素并返回一个新数组

  • slice() 方法返回数组一部分的浅拷贝。

  • 返回一个新数组,并且不会修改原始数组

//array.slice(start,end);
//start 为提取元素起始位置的索引(包括该索引对应的元素);
//end 是提取元素结束位置的索引(不包括该索引对应的元素);
//如果未指定 end 参数,则提取从起始索引位置到数组末尾的所有元素。

//1.提取指定范围内的元素
const fruits = ['apple', 'banana', 'kiwi', 'orange', 'grape'];
const slicedElements = fruits.slice(1, 4);
console.log(slicedElements);  // ['banana', 'kiwi', 'orange']

//2.提取指定位置到数组末尾的元素
const numbers = [1, 2, 3, 4, 5];
const slicedElementsToEnd = numbers.slice(2);
console.log(slicedElementsToEnd);  // [3, 4, 5]

//3.复制数组
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = originalArray.slice();
console.log(copiedArray);  // [1, 2, 3, 4, 5]

7、splice

功能:删除、替换或添加元素到数组的指定位置。

//array.splice(start,deleteCount,item1,item2,...)
//start 是要修改的起始位置的索引;
//deleteCount 是要删除的元素数。
//您可以根据需要指定item1、item2等参数来插入新元素。
//如果未指定deleteCount,则删除从起始索引位置开始的所有元素。

//1.删除元素
const numbers = [1, 2, 3, 4, 5];
const deletedElements = numbers.splice(2, 2);
console.log(numbers);          // [1, 2, 5]
console.log(deletedElements);  // [3, 4]

//2.更换元素
const fruits = ['apple', 'banana', 'kiwi'];
const replacedElements = fruits.splice(1, 1, 'orange', 'grape');
console.log(fruits);             // ['apple', 'orange', 'grape', 'kiwi']
console.log(replacedElements);   // ['banana']

//3.插入元素
const colors = ['red', 'blue', 'green'];
colors.splice(1, 0, 'yellow', 'purple');
console.log(colors);  // ['red', 'yellow', 'purple', 'blue', 'green']

8、join

功能:使用指定的分隔符将数组中的所有元素连接成字符串。

//array.join(separator)
//分隔符是可选字符串参数,指定元素之间的分隔符,默认为逗号(,)

//1.数组之间用“-”分隔
const fruits = ['apple', 'banana', 'kiwi'];
const joinedString = fruits.join('-');
console.log(joinedString);  // "apple-banana-kiwi"

//2.默认使用逗号作为分隔符
const numbers = [1, 2,3, 4, 5];
const joinedStringDefault = numbers.join();
console.log(joinedStringDefault);  // "1,2,3,4,5"

9、indexOf

 功能:返回指定元素在数组中第一次出现的索引,如果没有找到则返回-1。

//array.indexOf(searchElement,formIndex)

//1.搜索数组项第一次出现时的下标位置
const fruits = ['apple', 'banana', 'kiwi', 'banana', 'orange'];
const index = fruits.indexOf('banana');
console.log(index);  // 1

//2.从指定位置开始从前向后查找数组项第一次出现的下标位置
const numbers = [1, 2, 3, 4, 5, 3, 2, 1];
const indexFromIndex = numbers.indexOf(3, 3);
console.log(indexFromIndex);  // 5

 10、lastIndexOf

功能:返回指定元素在数组中最后一次出现的索引,如果没有找到则返回-1。

//array.lastIndexOf(searchElement,formIndex)
//searchElement表示要查找的元素,
//fromIndex则是起始查找位置。
//如果没有设置fromIndex,则默认从数组末尾开始查找。
//该方法返回最后一个匹配的元素的位置,若没有找到,则返回-1。

//1.搜索数组项最后一次出现时的下标位置
const fruits = ['apple', 'banana', 'kiwi', 'banana', 'orange'];
const lastIndex = fruits.lastIndexOf('banana');
console.log(lastIndex);  // 3

//2.从指定索引位置开始从后向前查找第一个出现的下标位置
const numbers = [1, 2, 3, 4, 5, 3, 2, 1];
const lastIndexFromIndex = numbers.lastIndexOf(3, 4);
console.log(lastIndexFromIndex);  // 2

 11、forEach

功能:对数组中的每个元素执行指定的函数,不返回新数组。

//forEach()方法不能中断或跳过迭代。

12、map

功能:对数组中的每个元素执行指定的函数,并返回由执行结果组成的新数组

//array.map(callback(element,index,array));
//callback是回调函数

const numbers = [1,2,3,4,5,6];
const doubledNumbers = numbers.map(el=>el * 2);
console.log(doubledNumbers );  // [2,4,6,8,10,12]

13、filter

功能:根据指定条件过滤掉数组中符合条件的元素,返回一个新数组

//array.filter(callback(element,index,array));

const numbers = [1,2,3,4,5,6];
const oddNumbers = numbers.filter(el=> el%2);
console.log(oddNumbers );  // [1,3,5]

14、reduce

功能:对数组中的所有元素执行指定的归约函数,并返回单值结果。将数组缩减为单个值。

//array.reduce(callback(accumulator,currentValue,index,array));
//参数说明:callback是回调函数,可以接受四个参数:
//accumulator:累加器,用于保存计算结果。
//currentValue:当前遍历的元素。
//index:当前遍历元素的索引。
//array:正在遍历的数组。

const numbers = [2,3,1,4];
let result = numbers.reduce((sum, current) => sum + current, 2);  
console.log(result);//12

15、sort

功能:对数组元素进行排序。

//1.不传递参数调用sort,会直接修改原数组,返回排序后的数组
const fruits = ['banana','apple','kiwi','pear'];
fruits.sort();
console.log(fruits); //['apple','banana','kiwi','pear']

//2.传入比较函数,该函数接受两个参数,返回一个代表比较结果的数字
const numbers = [10,5,8,2,3];
numbers.sort((a,b)=>a-b);
console.log(numbers );  // [2,3,5,8,10]

16、reverse

功能:反转数组中元素的顺序。会直接修改原数组,不会创建新数组

//reverse会直接修改原数组,不会返回新数组,可以使用slice()先复制一个新数组,再reverse
const numbers = [1,2,3,4,5];
const reversedNumbers = numbers.slice().reverse();
console.log(numbers);  // [1,2,3,4,5]
console.log(reversedNumbers);  //[5,4,3,2,1]

17、includes

功能:判断数组是否包含指定元素,返回true或false。

//array.includes(searchElement,formIndex)

//1. 检查数组是否包含特定元素
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3));  // true
console.log(numbers.includes(6));  // false

//2.使用fromIndex参数指定搜索的起始位置
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3, 2));  // true, search starts from index 2
console.log(numbers.includes(3, 4));  // false, search starts from index 4

//3. 检查数组中是否包含字符串
const fruits = ['apple', 'banana', 'kiwi', 'pear'];
console.log(fruits.includes('banana'));  // true
console.log(fruits.includes('grape'));   // false

18、some

功能:检查数组中是否至少有一个元素满足指定条件,返回true或false。

//array.some(callback(element,index,array));

//1、检查数组中是否有大于10的元素
const numbers = [5, 8, 12, 3, 9];
const hasGreaterThan10 = numbers.some(element => element > 10);
console.log(hasGreaterThan10);  // true

//2. 检查数组中是否有偶数
const numbers = [3, 7, 5, 12, 9];
const hasEvenNumber = numbers.some(element => element % 2 === 0);
console.log(hasEvenNumber);  // true

//3. 检查数组中是否存在包含特定字符的字符串
const fruits = ['apple', 'banana', 'kiwi', 'pear'];
const hasStrWithChar = fruits.some(element => element.includes('a'));
console.log(hasStrWithChar);  // true

//4、检查数组中是否存在满足复杂条件的元素
const students = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 92 },
  { name: 'Charlie', score: 76 },
];
const hasPassingScore = students.some(student => student.score >= 80);
console.log(hasPassingScore);  // true

19、every

功能:检查数组中所有元素是否满足指定条件,返回true或false。

//array.every(callback(element,index,array));

//1.检查数组中的所有元素是否都大于 0
const numbers = [5, 8, 12, 3, 9];
const allGreaterThan0 = numbers.every(element => element > 0);
console.log(allGreaterThan0);  // true

//2.检查数组中的所有元素是否都是偶数
const numbers = [2, 4, 6, 8, 10];
const allEvenNumbers = numbers.every(element => element % 2 === 0);
console.log(allEvenNumbers);  // true

//3.检查数组中的所有字符串是否以大写字母开头
const words = ['Apple', 'Banana', 'Cherry', 'Durian'];
const allUpperCaseStart = words.every(element => /^[A-Z]/.test(element));
console.log(allUpperCaseStart);  // true

//4.检查数组中的所有对象是否满足特定条件
const students = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 92 },
  { name: 'Charlie', score: 76 },
];
const allPassingScore = students.every(student => student.score >= 80);
console.log(allPassingScore);  // false

 20、toString

功能:toString() 方法返回一个由逗号分隔的字符串。 它不会修改原始数组


const colors = ["Red", "Green", "Blue", "Yellow", "Purple"];
console.log(colors.toString( )); //"Red, Green, Blue, Yellow, Purple"

21.、find

ES5 使用 indexOf() 和 lastIndexOf() 方法来查找数组中的元素。 find() 方法是在 ES6 中引入的。

功能:返回数组中满足条件的第一个元素的。如果没有找到合适的元素,则返回 undefined。

let numbers = [1, 3, 4, 6, 7];
console.log(numbers.find(e => e % 2 == 0)); // 4

 22、findLast

功能:返回数组中满足条件的最后一个元素的。如果没有找到合适的元素,则返回 undefined。

let numbers = [1, 3, 4, 6, 7];
console.log(numbers.findLast(e => e % 2 == 0)); // 6

23、 findIndex

功能:返回数组中满足条件的第一个元素的索引如果没有找到合适的元素,则返回 -1。

let numbers = [1, 15, 7, 8, 10, 15];
let index = numbers.findIndex(number => number === 15);
console.log(index); // 1

24、findLastIndex

功能:返回数组中满足条件的最后一个元素的索引,如果没有找到合适的元素,则返回 -1。

let numbers = [1, 15, 7, 8, 10, 15];
let index = numbers.findLastIndex(number => number === 15);
console.log(index); // 5

 25、fill

功能:将数组中的所有元素更改为静态返回修改后的数组


let numbers = [1,2,3,4,5,6];

//1.fill(value)将数组中所有元素修改为value
let result = numbers.fill(0);
console.log(result);//[0,0,0,0,0,0]

//2.fill(value, start)将数组中从start开始的元素(包括start)修改为value
let result = numbers.fill(0,2);
console.log(result);//[1,2,0,0,0,0]

//3.fill(value, start, end) 
//将数组中从start开始的元素(包括start)到end结束的元素(不包括end)修改为value
let result = numbers.fill(0,2,4);
console.log(result);//[1,2,0,0,5,6]

26、reduceRight

功能:对数组中的所有元素从右到左执行指定的归约函数,从而产生一个输出值。


const list = [😀, 😫, 😀, 😫, 🤪];
list.reduceRight((⬜️, ⚪️) => ⬜️ + ⚪️); // 🤪 + 😫 + 😀 + 😫 + 😀

const list = [1, 2, 3, 4, 5];
list.reduceRight((total, item) => total + item, 0); // 15

27、 at

返回指定索引处的值。索引前加负号,表示从右向左找。

const list = [1, 2, 3, 4, 5];
console.log(list.at(1)); // 2
console.log(list.at(-1)); // 5
console.log(list.at(-2)); // 4

28、 copyWithin

复制数组中的数组元素,并返回修改后的新数组。

  • 第一个参数是开始复制元素的目标。
  • 第二个参数是开始复制元素的索引。
  • 第三个参数是停止复制元素的索引。
const list = [1, 2, 3, 4, 5];
const result = list.copyWithin(0, 3, 4); 
console.log(result);// [4,2,3,4,5]

const list = [1, 2, 3, 4, 5,6];
const result = list.copyWithin(0, 3, 5); 
console.log(result);// [4,5,3,4,5,6]

29、 flat

返回一个新数组,其中所有子数组元素递归连接到指定深度。

const list = [1, 2, [3, 4, [5, 6]]];
const result = list.flat(Infinity); 
console.log(result);// [1, 2, 3, 4, 5, 6]

30、 flatMap

 返回通过将给定的回调函数应用于数组的每个元素而形成的新数组。

const list = [1, 2, 3];
const result = list.flatMap((el) => [el, el * el]);
console.log(result); // [1, 1, 2, 4, 3, 9]

31、 Array.from

从类数组或可迭代对象创建一个新数组。

const list = "123456";
let result =Array.from(list); 
console.log(result);//[1,2,3,4,5,6]

const range = (n) => Array.from({ length: n }, (_, i) => i + 1);
console.log(range(10)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

32、 Array.of()

使用可变数量的参数创建一个新数组,而不管参数的数量或类型。

const list = Array.of(1, 2, 3, 4, "apple",{name:"Lucy",age:18});
console.log(list);//[1,2,3,4,"apple",{"name": "Lucy","age": 18}]

33、Array.isArray()

如果给定值是一个数组,则返回 true。

const list = Array.isArray([1, 2, 3, 4, 5]);
console.log(list); // true
const list2 = Array.isArray(5); 
console.log(list2);// false

  • 25
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值