js截取数组的前三个
有多种方法可以截取数组的前三个元素,以下是其中的一种方法:
- 使用slice()方法:
const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.slice(0, 3);
console.log(slicedArr); // [1, 2, 3]
- 使用ES6的解构赋值:
const arr = [1, 2, 3, 4, 5];
const [first, second, third] = arr;
console.log([first, second, third]); // [1, 2, 3]
- 使用splice()方法:
const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.splice(0, 3);
console.log(slicedArr); // [1, 2, 3]
console.log(arr); // [4, 5]
这些方法都可以截取数组的前三个元素,你可以根据自己的需求选择适合的方法
原文地址: https://www.cveoy.top/t/topic/hLmr 著作权归作者所有。请勿转载和采集!