Array方法总结(三)

Array.prototype.slice()

返回一个新的数组对象。从原数组的start和end(不包括end)索引范围内浅拷贝。

slice(start, end)

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);

// fruits 包含 ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus 包含 ['Orange','Lemon']

Array.prototype.some()

数组中是否至少有一个元素通过了由提供的函数实现的测试。

const arr = [6, 10, 7];
const even = (element) => element % 2 === 0;
console.log(arr.some(even)); // true

Array.prototype.sort()

就地对数组的元素进行排序,并返回相同数组的引用。默认排序是将元素转换为字符串,然后按照UTF-16码元值升序排序。

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months); // ['Dec', 'Feb', 'Jan', 'March']

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1); // [1, 100000, 21, 30, 4]

Array.prototype.toSorted()

返回一个新数组,其元素按升序排列。

const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]

Array.prototype.splice()

移除或替换已存在的元素,或添加新元素。改变原数组。返回值是一个包含了删除的元素的数组。

splice(start, deleteCount, item1)

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months); // ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
console.log(months); // // ["Jan", "Feb", "March", "April", "May"]

从索引 0 处移除 2 个元素,并插入“parrot”、“anemone”和“blue”
const myFish = ["angel", "clown", "trumpet", "sturgeon"];
const removed = myFish.splice(0, 2, "parrot", "anemone", "blue");
console.log(myFish); // ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
console.log(removed); // ["angel", "clown"]

Array.prototype.toSpliced()

返回一个新数组,并在给定的索引处删除和/或替换了一些元素。

const months = ["Jan", "Mar", "Apr", "May"];

const months2 = months.toSpliced(1, 0, "Feb");
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]

const months3 = months2.toSpliced(2, 2);
console.log(months3); // ["Jan", "Feb", "May"]

const months4 = months3.toSpliced(1, 1, "Feb", "Mar");
console.log(months4); // ["Jan", "Feb", "Mar", "May"]

console.log(months); // ["Jan", "Mar", "Apr", "May"]

Array.prototype.toString()

返回一个字符串,表示指定的数组及其元素。

const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString()); // "1,2,a,1a"

Array.prototype.with()

返回一个新数组,其指定索引处的值会被新值替换。

arrayInstance.with(index, value)

const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]

const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6).map((x) => x ** 2)); // [1, 4, 36, 16, 25]

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值