返回
直击数组不变身九大法宝
前端
2023-10-30 14:41:06
不会改变自身の数组方法(9 个)
本篇文章带大家了解九个基于ES7的数组不变身的方法,包含concat、join、slice、toString、toLocaleString、indexOf、lastIndexOf、toSource和include。
concat
concat 方法用于连接两个或多个数组。
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1.concat(arr2);
console.log(arr3); // 输出: [ 1, 2, 3, 4, 5, 6 ]
concat 方法不会改变原数组 arr1 和 arr2。
join
join 方法用于将数组元素连接成字符串。
const arr = [1, 2, 3];
const str = arr.join(",");
console.log(str); // 输出: "1,2,3"
join 方法不会改变原数组 arr。
slice
slice 方法用于截取数组的一部分。
const arr = [1, 2, 3, 4, 5];
const newArr = arr.slice(1, 3);
console.log(newArr); // 输出: [ 2, 3 ]
slice 方法不会改变原数组 arr。
toString
toString 方法用于将数组转换为字符串。
const arr = [1, 2, 3];
const str = arr.toString();
console.log(str); // 输出: "1,2,3"
toString 方法不会改变原数组 arr。
toLocaleString
toLocaleString 方法用于将数组转换为本地化的字符串。
const arr = [1, 2, 3];
const str = arr.toLocaleString();
console.log(str); // 输出: "1,2,3"
toLocaleString 方法不会改变原数组 arr。
indexOf
indexOf 方法用于查找数组中某个元素的索引。
const arr = [1, 2, 3, 4, 5];
const index = arr.indexOf(3);
console.log(index); // 输出: 2
indexOf 方法不会改变原数组 arr。
lastIndexOf
lastIndexOf 方法用于查找数组中某个元素的最后一个索引。
const arr = [1, 2, 3, 4, 5, 3];
const index = arr.lastIndexOf(3);
console.log(index); // 输出: 5
lastIndexOf 方法不会改变原数组 arr。
toSource
toSource 方法用于返回数组的源代码。
const arr = [1, 2, 3];
const str = arr.toSource();
console.log(str); // 输出: "[1, 2, 3]"
toSource 方法不会改变原数组 arr。
include
include 方法用于判断数组中是否包含某个元素。
const arr = [1, 2, 3];
const result = arr.includes(2);
console.log(result); // 输出: true
include 方法不会改变原数组 arr。