js中数组常用的方法

javascript(js)中数组常用的方法

1.push():向数组末尾添加一个或多个元素,并返回新数组的长度。

const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]

2.pop():移除数组末尾的元素,并返回被移除的元素。

const arr = [1, 2, 3];
const poppedElement = arr.pop(); // 3, arr变为[1, 2]

3.unshift():向数组开头添加一个或多个元素,并返回新数组的长度。

const arr = [2, 3, 4];
arr.unshift(1); // [1, 2, 3, 4]

4.shift():移除数组开头的元素,并返回被移除的元素。

const arr = [1, 2, 3];
const shiftedElement = arr.shift(); // 1, arr变为[2, 3]

5.合并两个或多个数组,返回一个新数组。concat()

const arr1 = [1, 2];
const arr2 = [3, 4];
const mergedArray = arr1.concat(arr2); // [1, 2, 3, 4]

 6.从数组中截取指定范围的元素,返回一个新数组。slice()

const arr = [1, 2, 3, 4, 5];
const slicedArray = arr.slice(1, 4); // [2, 3, 4]

7.从数组中添加、删除或替换元素,原数组会被修改,并返回被删除的元素组成的数组。splice()

const arr = [1, 2, 3, 4, 5];
const removedElements = arr.splice(1, 2, 6, 7); // [2, 3], arr变为[1, 6, 7, 4, 5]

8.查找指定元素在数组中的第一个索引,如果不存在则返回-1。indexOf()

const arr = [1, 2, 3, 4, 3];
const index = arr.indexOf(3); // 2

9.查找指定元素在数组中的最后一个索引,如果不存在则返回-1。lastIndexOf()

const arr = [1, 2, 3, 4, 3];
const lastIndex = arr.lastIndexOf(3); // 4

10.检查数组是否包含指定元素,返回一个布尔值。includes()

const arr = [1, 2, 3, 4, 5];
const includesElement = arr.includes(3); // true

11.遍历数组的每个元素并执行回调函数。forEach()

const arr = [1, 2, 3];
arr.forEach((element) => {
  console.log(element);
});
// Output:
// 1
// 2
// 3

12.创建一个新数组,其中的元素为原数组元素经过回调函数处理后的值。map()

const arr = [1, 2, 3];
const squaredArr = arr.map((element) => element * element); // [1, 4, 9]

13.创建一个新数组,其中包含满足回调函数条件的元素。filter()

const arr = [1, 2, 3, 4, 5];
const evenNumbers = arr.filter((element) => element % 2 === 0); // [2, 4]

14.对数组中的元素进行累积计算,返回一个最终结果。reduce()

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, current) => acc + current, 0); // 15

生成数组

1.数组字面量:

const numbers = [1, 2, 3, 4, 5];

2.Array构造函数:

const numbers = new Array(1, 2, 3, 4, 5);

3.使用Array.from()方法:

const numbers = Array.from([1, 2, 3, 4, 5]);

这个是es6的新语法!!

4.Array.from()方法生成连续数字的数组:

const numbers = Array.from({ length: 5 }, (_, index) => index + 1);
// Output: [1, 2, 3, 4, 5]

5.Array.from()方法生成指定范围内的数字数组:

const start = 1;
const end = 5;
const numbers = Array.from({ length: end - start + 1 }, (_, index) => index + start);
// Output: [1, 2, 3, 4, 5]

6.Array.fill()方法生成指定长度和初始值的数组:

const length = 5;
const initialValue = 0;
const numbers = new Array(length).fill(initialValue);
// Output: [0, 0, 0, 0, 0]

7.Array.keys()方法生成数组的索引数组:

const numbers = [1, 2, 3, 4, 5];
const indices = Array.from(numbers.keys());
// Output: [0, 1, 2, 3, 4]

8.递归生成数组(不建议在大型数组中使用):

function generateArray(length) {
  if (length === 0) {
    return [];
  } else {
    return [...generateArray(length - 1), length];
  }
}

const numbers = generateArray(5);
// Output: [1, 2, 3, 4, 5]

打乱数组

要打乱数组中的元素顺序,可以使用不同的随机化算法。以下是常见的打乱数组的方法之一,称为Fisher-Yates 洗牌算法(也称为 Knuth 洗牌算法):

function shuffleArray(array) {
  const shuffledArray = array.slice(); // 复制原数组以防止修改原数组

  for (let i = shuffledArray.length - 1; i > 0; i--) {
    const randomIndex = Math.floor(Math.random() * (i + 1));
    [shuffledArray[i], shuffledArray[randomIndex]] = [shuffledArray[randomIndex], shuffledArray[i]];
  }

  return shuffledArray;
}
const originalArray = [1, 2, 3, 4, 5];
const shuffledArray = shuffleArray(originalArray);
console.log(shuffledArray); // 例如:[4, 1, 5, 2, 3]

此方法通过遍历数组,随机选择一个索引,并将当前位置的元素与随机位置的元素交换,直到遍历完整个数组,从而实现了数组元素的随机排列。

请注意,Fisher-Yates 洗牌算法是一种有效的随机化算法,并且具有相等的概率生成每一种可能的排列。这个算法在处理较大数组时也比较高效。

数组去重

1.使用set()(ES6及以上):

const originalArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(originalArray)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

2.使用indexOf()和filter()方法:

const originalArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = originalArray.filter((value, index, self) => self.indexOf(value) === index);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

3.使用includes()和filter()方法(ES6及以上):

const originalArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = originalArray.filter((value, index, self) => self.includes(value, index + 1) === false);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

4.使用reduce()方法(ES6及以上):

const originalArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = originalArray.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

 

多数组取交集

1.使用reduce()和filter()方法:

function arraysIntersection(arrays) {
  if (arrays.length === 0) return [];

  return arrays.reduce((result, currentArray) => {
    return result.filter(element => currentArray.includes(element));
  });
}

const array1 = [1, 2, 3, 4];
const array2 = [2, 3, 4, 5];
const array3 = [3, 4, 6];
const intersection = arraysIntersection([array1, array2, array3]);
console.log(intersection); // Output: [3, 4]

2.使用Set(ES6及以上):

function arraysIntersection(arrays) {
  if (arrays.length === 0) return [];

  const set = new Set(arrays[0]);

  for (let i = 1; i < arrays.length; i++) {
    const currentArray = new Set(arrays[i]);
    for (const element of set) {
      if (!currentArray.has(element)) {
        set.delete(element);
      }
    }
  }

  return Array.from(set);
}

const array1 = [1, 2, 3, 4];
const array2 = [2, 3, 4, 5];
const array3 = [3, 4, 6];
const intersection = arraysIntersection([array1, array2, array3]);
console.log(intersection); // Output: [3, 4]

 

posted @ 2023-07-18 14:47  上官靖宇  阅读(229)  评论(0编辑  收藏  举报