TS中常用数组的处理方法整理

1.遍历数组

//举例数组、一下方法通用
const array = [1, 2, 3, 4, 5];
  • 使用for...of循环:

for (const element of array) {
    console.log('',element);
}
  • 使用forEach()方法:

array.forEach(element => {
    console.log('',element);
});
  • 使用map()方法:

const newArray = array.map(element => element * 2);
console.log('',newArray); // [2, 4, 6, 8, 10]
  • 使用filter()方法:

const filteredArray = array.filter(element => element % 2 === 0);
console.log('',filteredArray); // [2, 4]
  • 使用reduce()方法:

const sum = array.reduce((acc, curr) => acc + curr, 0);
console.log('',sum); // 15

2.添加/删除/替换元素

  • 使用push()在数组末尾添加元素:

array.push(6);
console.log('',array); // [1, 2, 3, 4, 5, 6]
  • 使用pop()从数组末尾删除元素:

const poppedElement = array.pop();
console.log('',poppedElement); // 6console.log(array); // [1, 2, 3, 4, 5]
  • 使用unshift()在数组开头添加元素:

array.unshift(0);
console.log('',array); // [0, 1, 2, 3, 4, 5]
  • 使用shift()从数组开头删除元素:

const shiftedElement = array.shift();
console.log('',shiftedElement); // 0console.log(array); // [1, 2, 3, 4, 5]
  • 使用splice()进行元素的删除、替换、插入操作:

array.splice(2, 1); // 从索引 2 开始删除 1 个元素
console.log('',array); // [1, 2, 4, 5]

3.查找/获取元素

  • 使用indexOf()lastIndexOf()查找元素的索引:

const index = array.indexOf(3);
console.log('',index); // 2
  • 使用find()findIndex()查找符合条件的第一个元素或其索引:

const foundElement = array.find(element => element > 3);
console.log('',foundElement); // 4
  • 使用includes()判断数组是否包含某个元素:

const isIncluded = array.includes(2);
console.log('',isIncluded); // true
  • 使用slice()获取数组的子数组:

const subArray = array.slice(1, 3); // 获取索引 1 到 3(不包含索引 3)之间的元素
console.log('',subArray); // [2, 3]

4.数组操作

  • 使用concat()连接两个数组:

const array2 = [6, 7, 8];
const concatenatedArray = array.concat(array2);
console.log('',concatenatedArray); // [1, 2, 3, 4, 5, 6, 7, 8]
  • 使用join()将数组元素连接成字符串:

const joinedString = array.join(', ');
console.log('',joinedString); // "1, 2, 3, 4, 5"
  • 使用reverse()翻转数组元素的顺序:

array.reverse();
console.log('',array); // [5, 4, 3, 2, 1]
  • 使用sort()对数组元素进行排序:

array.sort((a, b) => a - b); // 升序排序
console.log('',array); // [1, 2, 3, 4, 5]

5.其他操作

  • 使用isArray()检查一个变量是否为数组:

const isArray = Array.isArray(array);
console.log('',isArray); // true
  • 使用Array.from()将类数组对象或可迭代对象转换为数组:

const arrayLikeObject = {0: 'a', 1: 'b', 2: 'c', length: 3};
const newArrayFromObject = Array.from(arrayLikeObject);
console.log('',newArrayFromObject); // ["a", "b", "c"]
  • 使用扩展运算符...进行数组的展开操作:

const arrayCopy = [...array];

console.log('',arrayCopy); // [1, 2, 3, 4, 5]
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值