This time I will bring you JavaScriptarray usagecollection,JavaScript arraywhat are the precautionsfor using collections, the following is a practical case, let’s take a look take a look.
1.join() Convert all elements in the array into strings and join them together
var a=[1,2,3,4]; a.join(); //"1,2,3,4"
2.reverser() Reverse the order of the elements in the array and return the array in reverse order.
var a[1,2,3,4]; a.reverse(); //[4,3,2,1]
3.sort() Sorts the elements in the array and returns the sorted array.
When sort() is called without parameters, the array elements are sorted in alphabetical order.
var a=['ant','Bug','cat','Dog']; a.sort(); //["Bug", "Dog", "ant", "cat"] a.sort(function(s,t){ var s1=s.toLowerCase(); var t1=t.toLowerCase(); if(s1<t1) return -1; if(s1>t1) return 1; return 0});//["ant", "BUg", "cat", "Dog"]
4.concat() creates and returns a new array whose elements include the elements of the original array calling concat() and each parameter of concat(). If any of these arguments is itself an array, the array elements are concatenated, not the arrays themselves.
var a=[1,2,3];a.concat(4,5);// [1, 2, 3, 4, 5]a.concat([4,5]);// [1, 2, 3, 4, 5]a.concat([4,5],[6,7]);// [1, 2, 3, 4, 5, 6, 7]a.concat([4,5],[6,[8,7]]);// [1, 2, 3, 4, 5, 6,[8,7]]
5.slice() returns a slice or subarray of the specified array. Its two parameters specify the start and end positions of the fragment respectively. The returned array contains all data elements between the position specified by the first argument and all up to but not including the position specified by the second argument.
If only one parameter is specified, the returned array contains all elements from the beginning to the end of the array.
If a negative number appears in the parameter, it represents the position relative to the last element in the array. For example: parameter -1 specifies the last element, and -3 specifies the third to last element.
Note that slice() will not modify the called array.
var a=[1,2,3,4,5];a.slice(0,2);//[1, 2]a.slice(3);//[4, 5]a.slice(1,-1);//[2, 3, 4]a.slice(-3,-2);//[3]
6.splice() A general method to insert or delete elements in an array. Unlike slice() and concat(), splice() modifies the calling array. Note: splice() and slice() have very similar names, but their functions are essentially different.
splice() can delete elements from an array, insert elements into an array, or complete both operations at the same time. Array elements after the insertion or deletion point have their index values increased or decreased as necessary, so the rest of the array remains contiguous. The first parameter of splice() specifies the starting position of insertion and/or deletion. The second parameter specifies the number of elements that should be deleted from the array. If the second parameter is omitted, all elements from the starting point to the end of the array will be deleted. splice() returns an array of deleted elements, or an empty array if no elements were deleted.
var a=[1,2,3,4,5,6,7,8];a.splice(4);//返回[[5, 6, 7, 8]],a是[1, 2, 3, 4]a.splice(1,2)//返回[2, 3],a是[1, 4, 5, 6, 7, 8]a.splice(1,1);//返回[2],a是 [1, 3, 4, 5, 6, 7, 8]
7.push() and pop()
push() adds one or more elements to the end of the array.
pop() deletes the last element of the array.
8.unshift() and shift()
unshift() adds one or more elements to the head of the array.
shift() deletes the first element of the array.
9.toString() and toLocaleString()
[1,2,3].toString();//"1,2,3"[1,[2,'c']].toString();//"1,2,c"
toLocaleString() is the localized version of the toString() method. It calls the element's toLocaleString() method to convert each array element to a string, and concatenates these strings using localized delimiters to generate the final string.
10.forEach() traverses the array from beginning to end and calls the specified function for each element.The function passed is the first parameter of forEach(), and then forEach() calls the function with three parameters: the array element, the index of the element and the array itself.
var data=[1,2,3,4,5];//计算数组元素的和值var sum=0; data.forEach(function(value){ sum+=value }); sum //15//每个数组元素的值加1data.forEach(function(value,index,arr){ arr[index]=value+1; }); data //[2, 3, 4, 5, 6]11.map() passes each element of the called array to the specified function and returns an array containing the return value
of the function. Note: The function passed to mao() should have a return value. map() returns a new array and does not modify the original array. If the original array is a sparse array, the sparse array returned is the same way, with the same length and the same missing elements.
var a=[1,2,3];var b=a.map(function(value){return value*value; }); b// [1, 4, 9]12 filter() returns the array elements that meet the conditions
var a=[1,2,3,5];var b=a.filter(function(value){return value>2; }); b // [3, 5]13.every() and some()
The logical judgment of the array, they apply the specified function to the array elements Determine, return true or false.
every() means that all elements in the array meet the filtering conditions, then return true.
some() means that there are elements in the array that meet the filtering conditions, then return true;
var a =[1,2,3,4,5]; a.every(function(value){return value<10; }) //true a中所有元素都小于10a.every(function(value){return value%2===0; });//false a中不是所有元素都是偶数a.some(function(value){return value%2===0; })//true a中存在偶数reduce() and reduceRight()
Use the specified function to combine array elements to generate a single value.
reduce() requires two parameters.
The first one is the function that performs the simplification operation. The task of the simplify function is to combine or simplify two values into one value in some way and return the simplified value. The second (optional) parameter is an initial value passed to the function.
reduceRight() is used in the same way as reduce(), except that it processes the array from high to low (right to left) according to the array index.
var a=[1,2,3,4,5];var sum=a.reduce(function(x,y){return x+y;},0); sum //15 数组求和var max=a.reduce(function(x,y){return x>y?x:y}); max // 5求最大值indexOf() and lastIndexOf()
indexOf()The index of the first qualifying value, if not, returns -1
lastIndexOf()The index of the last qualifying value , if not, return -1
Detailed explanation of Require.js
How to implement node connection to mysql
How to use JS regular expressions
Javascript’s singleton pattern
The above is the detailed content of JavaScript arrays using collections. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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.

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool