Home  >  Article  >  Web Front-end  >  Classic techniques for JavaScript array operations (organized and shared)

Classic techniques for JavaScript array operations (organized and shared)

WBOY
WBOYforward
2022-01-13 17:55:501344browse

This article brings you some related operations on arrays in JavaScript, mainly including Array object prototype methods and common operations such as deduplication, flattening, sorting, etc. I hope it will be helpful to you.

Classic techniques for JavaScript array operations (organized and shared)

JavasScript array operations, mainly including Array object prototype methods and common operations such as deduplication, flattening, sorting, etc.

Array. prototype

forEach

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

  • callback is a function executed for each element in the array. This function receives one to three parameters

  • currentValue is being processed in the array Waiting for the index of the current element

  • array optional [indicates the array being operated on]

  • thisArg optional [when executing the callback function, use As the value of this, this parameter will be ignored when using arrow functions]

forEach() executes the given function once for each element of the array

let arr = [1, 2, 3, 4, 5];
let obj = {a: 1};
arr.forEach(function(currentValue, index, array) {
  console.log("当前值:", currentValue);// 1
  console.log("当前值索引:", index);// 0
  console.log("当前处理数组:", array); // (5)[1, 2, 3, 4, 5]
  console.log("当前this指向:", this);// {a: 1}
  console.log("结束一次回调, 无需返回值");
  console.log("");
}, obj);
console.log(arr);// [1, 2, 3, 4, 5]不改变原数组

map

arr.map(callback(currentValue [, index [, array]])[, thisArg])

  • callback is a function executed by each element of the array. The function receives one to three parameters

  • currentValueThe current element being processed in the array

  • index optional [index of the current element being processed in the array]

  • array optional [array being operated on]

  • thisArg optional Select [When executing the callback function, use it as the value of this, this function will be ignored when using the arrow function]

##map() creates a new array, the result of which is the array The return value after each element in the function is called once

let arr = [1, 2, 3, 4, 5];
let obj = {a: 1};
let newArr = arr.map(function(currentValue, index, array) {
  console.log("当前值:", currentValue);// 1
  console.log("当前值索引:", index);// 0
  console.log("当前处理数组:", array); // (5)[1, 2, 3, 4, 5]
  console.log("当前this指向: ", this); // {a: 1}
  console.log("");
  return crrentValue + 10;
}, obj);
console.log(newArr);// [11, 12, 13, 14, 15]
console.log(arr);// [1, 2, 3, 4, 5]不改变原数组

push

arr.push(element1[,. .., elementN])

elementN is the element that is added to the end of the array

push() adds one or more elements to the end of the array and returns the length of the array

let arr = ['a', 'b', 'c', 'd', 'e'];
console.log(arr.push('f', 'g'));// 7
console.log(arr);// ["a", "b", "c", "d", "e", "f", "g"] 改变原数组

pop

pop() deletes the last element from the array and returns the value of the element. When the array is empty, undefind is returned. This method Change the length of the array

let arr = [1, 2, 3, 4, 5];
console.log(arr.pop());// 5
console.log(arr);// [1, 2, 3, 4] 改变原数组

shift

shift() removes the first element from the array and returns the value of the element, the The method will change the original array

let arr = [1, 2, 3, 4, 5]
console.log(arr.shift());// 1
console.log(arr);// [2, 3, 4, 5] 改变原数组

unshift##arr.unshift(element1[, ..., elementN])

unshift() adds one or more elements to the beginning of the array and returns the length of the array. This method modifies the original array

let arr = [1, 2, 3, 4, 5]
console.log(arr.unshift(-1, 0));// 7
console.log(arr);// [-1, 0, 1, 2, 3, 4, 5] 改变原数组

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

start specifies the starting position of the modification. If it exceeds the length of the array, then Add content starting from the end of the array; if it is a negative value, it indicates the number from the end of the array (counting from -1, which means -n is the nth element from the last and is equivalent to array.length-1); If the absolute value of the negative number is greater than the length of the array, it means that the starting position is position 0.

deleteCount is optional [integer], indicating the number of array elements to be removed. If deleteCount is greater than the total number of elements after start , then all elements after statr will be deleted (including the start bit). If deleteCount is omitted, or its value is greater than or equal to array.length-start (that is, if it is greater than or equal to all elements after start quantity), then all elements of the array will be deleted after start

item1, item2, ...optional [elements to be added to the array, starting from the start position. If not specified, splice() will Only delete array elements]

splice() modifies the array by deleting or replacing existing elements or adding new elements in place, and returns the modified content in the form of an array. This method will change the original array

let arr = [1, 2, 3, 4, 5]
console.log(arr.splice(1, 1));// [2]
console.log(arr);// [1, 3, 4, 5] 改变原数组

slicearr.slice([begin[, end]])

beginoptional[extraction start index] Extract the original array elements starting from this index. If this parameter is a negative number, it means starting to extract from the last few elements in the original array. If begin is omitted, the slice starts from index 0; if begin is greater than the original array length, an empty array will be returned.

end is optional [index at the end of extraction], and the extraction of the original array elements ends at this index. slice will extract all elements from the index from begin to end in the original array, including begin, but does not include end. If end is omitted, slice will be extracted to the end of the original array. If end is greater than the length of the array, slice will be extracted to the end of the array.

slice() returns a new Array object, this object is a shallow copy of the original array determined by begin and end, including begin, excluding end, the original array will not be changed

let arr = [1, 2, 3, 4, 5];
console.log(arr.sclice(1, 3));// [2, 3]
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

concat let new_array = old_array.concat(value[, value2[, ...[, valueN]]])

valueNoptional[], concatenate the array or value into New array, if the valueN parameter is omitted, concat will return a shallow copy of the existing array it is called

concat()用于合并两个或多个数组, 此方法不会更改现有数组, 而是返回一个新数组

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = arr1.concat(arr2);
console.log(arr3);// [1, 2, 3, 4, 5, 6]
console.log(arr1);// [1, 2, 3] 不改变原数组

join

arr.join([separator])

separator可选 指定一个字符串来分隔数组的每个元素

join()将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串. 如果数组只有一个项目, 那么将返回该项目而不使用分隔符

let arr = ['a', 'b', 'c'];
console.log(arr.join("&"));// a&b&c
console.log(arr);// ["a", "b", "c"] 不改变数组

sort

arr.sort([compareFunction])

compareFunction可选 用来指定按某种顺序进行排列的函数. 如果省略, 元素按照转换为第字符串的各个字符的Unicode进行排序

firstEl第一个用于比较的元素

secondEl第二个用于比较的元素

sort()用原地算法对数组的元素进行排序, 并返回数组. 默认排序顺序是在将元素转换为字符串, 然后比较它们的UTF-16代码单元值序列时构建的

let arr = [1, 2, 3, 4, 5];
console.log(arr.sort((a, b) => b - a));// [5, 4, 3, 2, 1]
console.log(arr);// [5, 4, 3, 2, 1] 改变原数组

reverse

reverse()将数组中元素的位置颠倒, 并返回该数组, 该方法会改变原数组

let arr = [1, 2, 3, 4, 5];
console.log(arr.reverse());// [5, 4, 3, 2, 1]
console.log(arr);// [5, 4, 3, 2, 1] 改变原数组

every

every()测试一个数组内的所有元素是否都能通过某个指定函数的测试, 返回一个布尔值

let arr = [1, 2, 3, 4, 5];
console.log(arr.every(currentValue => currentValue > 1));// false
console.log(arr);// 不改变原数组

some

some()测试数组中是不是至少有1个元素通过了提供的测试函数, 返回一个Boolean类型的值

let arr = [1, 2, 3 ,4 ,5];
console.log(arr.some(currentValue => currentValue > 1));// true
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

filter

filter()创建一个新数组, 其包含通过所提供的测试函数的所有元素

let arr = [1, 2, 3, 4, 5];
console.log(arr.filter(currentValue => currentValue > 2));// [3, 4, 5]
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

find

find()返回数组中满足提供的测试函数的第一个元素的值, 否则返回undefined

let arr = [1, 2, 3, 4, 5];
console.log(arr.find(currentValue => currentValue > 2));// 3
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

findIndex

findIndex()返回数组中满足提供的测试函数的第一个元素的索引, 否则返回-1

let arr = [1, 2, 3, 4, 5];
console.log(arr.findIndex(currentValue => currentValue > 2));// 2
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

includes

includes()用来判断一个数组是否包含一个指定的值, 如果包含则返回true, 否则返回false

let arr = [1, 2, 3, 4, 5];
console.log(arr.includes(2));// true
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

indexOf

indexof()返回指定元素在数组中的第一个索引, 否则返回-1

let arr = [1, 2, 3, 4, 5];
console.log(arr.indexOf(2));// 1
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

lastIndexOf

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

let arr = [1, 2, 3, 2, 1];
console.log(arr.lastIndexOf(2));// 3
console.log(arr);// [1, 2, 3, 2, 1] 不改变原数组

fill

fill()用一个固定值填充一个数组从起始索引到终止索引到全部元素, 不包括终止索引

let arr = [1, 2, 3, 4, 5];
console.log(arr.fill(0, 0, 5));// [0, 0, 0, 0, 0]
console.log(arr);// [0, 0, 0, 0 ,0] 改变数组

flat

flat()会按照一个可指定的深度递归遍历数组, 并将所有元素与遍历到的子数组中的元素合并为一个新数组返回

let arr = [1, 2, [3, 4, [5]]];
console.log(arr.flat(2));// [1, 2, 3, 4, 5]
console.log(arr);// [1, 2, [3, 4, [5]]] 不改变原数组

keys

keys()返回一个包含数组中每个索引键的Array Iterator对象

let arr = [1, 2, 3, 4, 5];
let iterator = arr.keys();
for (const key of iterator) {
  console.log(key);
  // 0
  // 1
  // 2
}
console.log(arr);// [1, 2, 3, 4, 5] 不改变原数组

常用操作

数组去重

使用对象

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let obj = {};
let newArr = [];
arr.forEach(v => {
  if(!ogj[v]) {
    ogj[v] = 1;
    newArr.push(v);
  }
})
console.log(newArr);// [1, 2, 3, 5]

使用Set

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let newArr = Array.from(new Set(arr));
// let newArr = [...(new Set(arr))];// 使用ES6解构赋值
console.log(newArr);// [1, 2, 3, 5]

扁平化数组

使用flat

let arr = [1, 2, [3, 4, [5]]];
let newArr = arr.flat(2);
console.log(newArr);// [1, 2, 3, 4, 5]

递归实现flat

function _flat(arr, maxN = 1, curN = 0) {
  let newArr = [];
  if (curN >= maxN) return arr;
  arr.forEach((v, i, array) => {
    if (Array.isArray(v)) {
      newArr.push(..._flat(v, maxN, curN + 1));
    } else newArr.push(v);
  })
  return newArr;
}
let arr = [1, 2, [3, 4, [5]]];
let newArr = _flat(arr, 1);// 扁平化一层
console.log(newArr);// [1, 2, 3, 4, [5]]

统计一个字符串中出现最多的字符

使用数组将字符的ASCII码作为key制作桶

let s = "ASASRKIADAA";
let arr = [];
let base = 65;// A-Z 65-90 a-z 97-122
Array.prototype.forEach.call(s, (v) => {
  let ascii = v.charCodeAt(0) - base;
  if (arr[ascii]) {
    ++arr[ascii];
  } else arr[ascii] = 1;
})
let max = 0;
let maxIndex = 0;
arr.forEach((v, i) => {
  if (v > max) {
    max = v;
    maxIndex = i;
  }
})
console.log(String.fromCharCode(maxIndex + base), arr[maxIndex]);// A 5

找出数组中的最大值

遍历数组

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let max = -Infinity;
arr.forEach(v => {
  if (v > max) max = v;
})
console.log(max);// 5

使用Math

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let max = Math.max(...arr);
console.log(max);// 5

使用reduce

let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3];
let max = arr.reduce((a, v) => {
  return a > v ? a : v;
})
console.log(max);// 5

拷贝数组

遍历数组使用push

let arr = [1, 2, 3, 4, 5];
let newArr = [];
arr.forEach(v => newArr.push(v));
console.log(newArr);// [1, 2, 3, 4, 5]

使用concat

let arr = [1, 2, 3, 4, 5];
let newArr = [].concat(arr);
console.log(newArr);// [1, 2, 3, 4, 5]

使用slice

let arr = [1, 2, 3, 4, 5];
let newArr = arr.slice(0);
console.log(newArr);// [1, 2, 3, 4, 5];

随机打乱一个数组

随机交换N次

function randomInt(a, b) {
  return Number.parseInt(Math.random() * (b-a) + a);
}
let arr = [1, 2, 3, 4, 5];
let N = arr.length;
arr.forEach((v, i, arr) => {
  let ran = randomInt(0, N);
  [arr[i], arr[ran]] = [arr[ran], arr[i]];
})
console.log(arr);

随机排序

let arr = [1, 2, 3, 4, 5];
arr.sort((v1, v2) => {
  return Math.random() >= 0.5 ? 1 : -1;
})
console.log(arr);

【相关推荐:javascript学习教程

The above is the detailed content of Classic techniques for JavaScript array operations (organized and shared). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete