Summary of ES5 and ES6 array methods
This article will share with you a summary of ES5 and ES6 array methods. Friends who need it can take a look at
Array object properties
constructor Return A reference to the array function that created this object.
length Sets or returns the number of elements in the array.
prototype gives you the ability to add properties and methods to objects.
Traditional Array object method
toSource() Returns the source code of the object.
toString() Converts the array to a string and returns the result.
toLocaleString() Converts the array to a local array and returns the result.
valueOf() Returns the original value of the array object
Modify the original array
push() Add to the end of the array One or more elements and returns the new length.
unshift() Adds one or more elements to the beginning of the array and returns the new length.
pop() Delete and return the last element of the array
shift() Delete and return the first element of the array
sort() Sort the elements of the array
reverse() reverses the order of elements in an array.
splice() Removes elements and adds new elements to the array.
splice
Syntax
arrayObject.splice(index,howmany,item1,...,itemX)
var arr = new Array(); arr[0] = "George"; arr[1] = "John"; arr[2] = "Thomas"; arr.splice(2,1); //"George", "John" arr.splice(1,0,"William"); //"George", "William", "John" arr.splice(2,1,"haha"); //"George", "William", "haha"
Do not modify the original array
concat() Concatenates two or more arrays and returns the result.
join() Put all elements of the array into a string. Elements are separated by the specified delimiter.
slice() Returns the selected element from an existing array
slice
Syntax
arrayObject.slice(start,end);
start Required. Specifies where to start the selection. Can be negative, counting from the end of the array.
end Optional. Specifies where the selection ends. If not specified, the sliced array contains all elements from start to the end of the array. Can be negative, counting from the end of the array.
var arr = new Array(); arr[0] = "George"; arr[1] = "John"; arr[2] = "Thomas"; arr.slice(2,1); //[] arr.slice(1,2); //"William" arr.slice(-2,-1); //"William"
Convert array-like objects (such as arguments) to real arrays
Array.prototype.slice.call(arguments);
ES5 new Array
Index methods: indexOf(), lastIndexOf()
Iteration methods: forEach(), map(), filter(), some(), every()
Merge method: reduce(), reduceRight()
The method will not modify the original array
Index method
indexOf
array.indexOf(searchElement[, fromIndex])
Returns the integer index value, if there is no match (strict match), returns -1.
fromIndex is optional, indicating that the search starts from this position. If the default or the format does not meet the requirements, use the default value 0.
var data = [2, 5, 7, 3, 5]; console.log(data.indexOf(5, "x")); // 1 ("x"被忽略) console.log(data.indexOf(5, "3")); // 4 (从3号位开始搜索)
lastIndexOf
array.lastIndexOf(searchElement[, fromIndex])
Search from the end of the string, not from the beginning.
The default value of fromIndex is array.length - 1.
var data = [2, 5, 7, 3, 5]; console.log(data.lastIndexOf(5)); // 4 console.log(data.lastIndexOf(5, 3)); // 1 (从后往前,索引值小于3的开始搜索) console.log(data.lastIndexOf(4)); // -1 (未找到)
The two methods will use the equality operator when comparing the first parameter with each item in the array. They must be completely equal, otherwise -1 will be returned.
Iteration method
Each method accepts two parameters, the first parameter is callback (callback function, required), and the second parameter is an optional context parameter.
The first parameter callback accepts three parameters, the value of the current item, the index of the current item in the array, and the array object itself. That is, function(value,index,arr) {}; it should be noted that the difference from the method encapsulated in our commonly used jQuery is the first parameter and the second parameter, that is, the order of index and value is reversed.
The second parameter is an optional context parameter, which is the scope object that executes the first function parameter, which is the value pointed to by this in the callback mentioned above. If the second optional parameter is not specified, the global object is used instead (window in browsers), or even undefined in strict mode.
It should be noted that except for the forEach() method, the callback in the other iteration methods needs to have a return value, otherwise undefined will be returned.
forEach
forEach() loops through the array and runs the given function on each item in the array. This method has no return value.
[].forEach(function(value, index, array) { // ... }, [ thisObject]);
In addition to accepting a required callback function parameter, forEach can also accept an optional context parameter (changing the this pointer in the callback function) (the second parameter).
If the second optional parameter is not specified, the global object will be used instead (window in the browser), or even undefined in strict mode.
[1, 2, 3, 4].forEach(function (item, index, array) { console.log(array[index] == item); // true sum += item; }); alert(sum); // 10 var database = { users: ["张含韵", "江一燕", "李小璐"], sendEmail: function (user) { if (this.isValidUser(user)) { console.log("你好," + user); } else { console.log("抱歉,"+ user +",你不是本家人"); } }, isValidUser: function (user) { return /^张/.test(user); } }; // 给每个人法邮件 database.users.forEach( // database.users中人遍历 database.sendEmail, // 发送邮件 database // 使用database代替上面标红的this ); // 结果: // 你好,张含韵 // 抱歉,江一燕,你不是本家人 // 抱歉,李小璐,你不是本家
map
map() refers to "mapping", which runs a given function on each item in the array and returns an array composed of the results of each function call.
[].map(function(value, index, array) { // ... }, [ thisObject]);
var data = [1, 2, 3, 4]; var arrayOfSquares = data.map(function (item) { return item * item; }); alert(arrayOfSquares); // 1, 4, 9, 16
filter
filter(),“过滤”,对数组中的每一项运行给定函数,返回满足过滤条件组成的数组。
array.filter(callback,[ thisObject]);
filter的callback函数需要返回布尔值true或false。
返回值只要是弱等于== true/false就可以了,而非非得返回 === true/false。
var arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var flag = arr3.filter(function(value, index) { return value % 3 === 0; }); console.log(flag); // [3, 6, 9]
every
every(),判断数组中每一项都是否满足所给条件,当所有项都满足条件,才会返回true。
array.every(callback,[ thisObject]);
var arr4 = [1, 2, 3, 4, 5]; var flag = arr4.every(function(value, index) { return value % 2 === 0; }); console.log(flag); // false
some
some(),判断数组中是否存在满足条件的项,只要有一项满足条件,就会返回true。
array.some(callback,[ thisObject]);
var arr5 = [1, 2, 3, 4, 5]; var flag = arr5.some(function(value, index) { return value % 2 === 0; }); console.log(flag); // true
归并方法
这两个方法相比前面可能稍微复杂一些,它们都会迭代数组中的所有项,然后生成一个最终返回值。这两个方法接收两个参数。
第一个参数callback,函数接受4个参数分别是(初始值total必选,当前值currentValue必选,索引值currentIndex可选,当前数组arr可选),函数需要返回一个值,这个值会在下一次迭代中作为初始值。
第二个参数是迭代初始值(initialValue),参数可选,如果缺省,初始值为数组第一项,从数组第一个项开始叠加,缺省参数要比正常传值少一次运算。
reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。 reduce() 对于空数组是不会执行回调函数的。
array. reduce(function(total, currentValue, currentIndex, array) { // ... });
var arr9 = [1, 2, 3, 4]; var sum9 =arr9.reduce(function (total, curr, index, array) { return total * curr; }); console.log(sum9); // 24 var sum9_1 =arr9.reduce(function (total, curr, index, array) { return total * curr; }, 10); console.log(sum9_1); // 240
reduceRight
reduceRight()和reduce()相比,用法类似,差异在于reduceRight是从数组的末尾开始实现的。
array.reduceRight(callback,[ thisObject]);
var arr9 = [2, 45, 30, 80]; var flag = arr9.reduceRight(function (total, curr, index) { return total - curr; }); var flag_1 = arr9.reduceRight(function (total, curr, index) { return total - curr; },200); console.log(flag); // 3 console.log(flag_1); // 43
相关推荐:
The above is the detailed content of Summary of ES5 and ES6 array methods. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values takes a relatively long time.

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.
