JS中的数组技巧

image.png


数组去重

数组去重是在使用JS时常见的问题,使用一个新的Set()可以更快的解决问题,这里有两种使用Set()的解决方案:

  1. .from()方法

    Array.from(arrayLike[, mapFn[, thisArg]])

    参数

    • arrayLike

      想要转换成数组的伪数组对象或可迭代对象。

    • mapFn 可选

      如果指定了该参数,新数组中的每个元素会执行该回调函数。

    • thisArg 可选

      可选参数,执行回调函数 mapFnthis 对象。

    返回值

    一个新的数组实例。

    Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。

    [ 示例 ]

    // [2, 4, 6]
    Array.from([1, 2, 3], x => x + x);
    <  ------------------------------------------------  >
    Array.from('foo');
    // [ "f", "o", "o" ]
    <  ------------------------------------------------  >
    const set = new Set(['foo', 'bar', 'baz', 'foo']);
    Array.from(set);
    // [ "foo", "bar", "baz" ]
    <  ------------------------------------------------  >
    const map = new Map([[1, 2], [2, 4], [4, 8]]);
    Array.from(map);
    // [[1, 2], [2, 4], [4, 8]]
    <  ------------------------------------------------  >
    function f() {
     return Array.from(arguments);
    }
    f(1, 2, 3);
    // [ 1, 2, 3 ]

  2. 使用spread操作符...

[ 示例 ]

var fruits = ["banana", "apple", "orange", "watermelon", "apple", "orange", "grape", "apple"];

// First method
var uniqueFruits = Array.from(new Set(fruits));
console.log(uniqueFruits);
// returns ["banana", "apple", "orange", "watermelon", "grape"]

// Second method
var uniqueFruits2 = […new Set(fruits)];
console.log(uniqueFruits2);
// returns ["banana", "apple", "orange", "watermelon", "grape"]

替换数组中的特定值

有时在创建代码时需要替换数组中的特定值,此时可以使用.splice()方法:

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组

参数

  • start

    指定修改的开始位置(从0计数)。如果超出了数组的长度,则从数组末尾开始添加内容;如果是负值,则表示从数组末位开始的第几位(从-1计数,这意味着-n是倒数第n个元素并且等价于array.length-n);如果负数的绝对值大于数组的长度,则表示开始位置为第0位。

  • deleteCount 可选

    整数,表示要移除的数组元素的个数。

    如果 deleteCount 大于 start 之后的元素的总数,则从 start 后面的元素都将被删除(含第 start 位)。

    如果 deleteCount 被省略了,或者它的值大于等于array.length - start(也就是说,如果它大于或者等于start之后的所有元素的数量),那么start之后数组的所有元素都会被删除。

    如果 deleteCount 是 0 或者负数,则不移除元素。这种情况下,至少应添加一个新元素。

  • item1, item2, *...* 可选

    要添加进数组的元素,从start 位置开始。如果不指定,则 splice() 将只删除数组元素。

返回值

由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组。

[ 示例 ]

var fruits = ["banana", "apple", "orange", "watermelon", "apple", "orange", "grape", "apple"];
fruits.splice(0, 2, "potato", "tomato");
console.log(fruits);
// returns ["potato", "tomato", "orange", "watermelon", "apple", "orange", "grape", "apple"]

映射数组

常见的方法是使用Map()方法,这里使用数组的.from()方法:

Array.from(arrayLike[, mapFn[, thisArg]])

Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。

参数

  • arrayLike

    想要转换成数组的伪数组对象或可迭代对象。

  • mapFn 可选

    如果指定了该参数,新数组中的每个元素会执行该回调函数。

  • thisArg 可选

    可选参数,执行回调函数 mapFnthis 对象。

返回值

一个新的数组实例。

[ 示例 ]

var friends = [
   { name: "John", age: 22 },
   { name: "Peter", age: 23 },
   { name: "Mark", age: 24 },
   { name: "Maria", age: 22 },
   { name: "Monica", age: 21 },
   { name: "Martha", age: 19 },
]
对我有帮助
75人认为有帮助

相关帮助