


Classic techniques for JavaScript array operations (organized and shared)
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.
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]
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 arraypush() 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 arraylet 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 arraylet 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!

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.