Home Web Front-end JS Tutorial JavaScript arrays using collections

JavaScript arrays using collections

Mar 14, 2018 am 10:27 AM
javascript js gather

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"
Copy after login

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]
Copy after login

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"]
Copy after login

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]]
Copy after login

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]
Copy after login

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]
Copy after login

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,&#39;c&#39;]].toString();//"1,2,c"
Copy after login

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]
Copy after login

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]
Copy after login

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]
Copy after login

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中存在偶数
Copy after login

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求最大值
Copy after login
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

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Why is it difficult to implement collection-like functions in Go language? Why is it difficult to implement collection-like functions in Go language? Mar 24, 2024 am 11:57 AM

It is difficult to implement collection-like functions in the Go language, which is a problem that troubles many developers. Compared with other programming languages ​​such as Python or Java, the Go language does not have built-in collection types, such as set, map, etc., which brings some challenges to developers when implementing collection functions. First, let's take a look at why it is difficult to implement collection-like functionality directly in the Go language. In the Go language, the most commonly used data structures are slice and map. They can complete collection-like functions, but

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

A Practical Guide to the Where Method in Laravel Collections A Practical Guide to the Where Method in Laravel Collections Mar 10, 2024 pm 04:36 PM

Practical Guide to Where Method in Laravel Collections During the development of the Laravel framework, collections are a very useful data structure that provide rich methods to manipulate data. Among them, the Where method is a commonly used filtering method that can filter elements in a collection based on specified conditions. This article will introduce the use of the Where method in Laravel collections and demonstrate its usage through specific code examples. 1. Basic usage of Where method

Java Iterator vs. Iterable: A step into writing elegant code Java Iterator vs. Iterable: A step into writing elegant code Feb 19, 2024 pm 02:54 PM

Iterator interface The Iterator interface is an interface used to traverse collections. It provides several methods, including hasNext(), next() and remove(). The hasNext() method returns a Boolean value indicating whether there is a next element in the collection. The next() method returns the next element in the collection and removes it from the collection. The remove() method removes the current element from the collection. The following code example demonstrates how to use the Iterator interface to iterate over a collection: Listnames=Arrays.asList("John","Mary","Bob");Iterator

See all articles