Summary of js array operations and parsing methods
This time I will bring you a summary of js array operation and parsing methods. What are the precautions for js array operation and parsing? The following is a practical case, let's take a look.
Preface
In development, there are many usage scenarios for arrays, and many api/related operations of arrays are also involved in daily life. There has never been any discussion on this content. Make a summary together. In many cases, even if you have used this API several times, it is easy to forget it during development, so you still need to Google it. So I hope to have a more systematic summary of this content. Against this background, this article is here. If you like it, you can like/follow it and support it. I hope everyone can gain something from reading this article.
Create an array:
1 2 3 4 5 6 7 8 |
|
ES6 Array.of() returns an array composed of all parameter values
Definition: Returns an array composed of all parameter values If there are no parameters, an empty array will be returned.
Purpose: The purpose of Array.of() is to solve the problem of different behaviors of the above constructors due to different number of parameters.
1 2 |
|
ES6 Arrar.from() Converts two types of objects into real arrays
Definition: Used to convert two types of objects into real arrays (does not change original object, returns a new array).
Parameters:
The first parameter (required): the object to be converted into a real array.
Second parameter (optional): An array-like map method that processes each element and puts the processed value into the returned array.
The third parameter (optional): used to bind this.
1 2 3 4 5 6 |
|
Methods:
The array prototype provides a lot of methods, which are divided into three categories. One type will change the value of the original array, and the other type will not change the original array. And array traversal methods.
Methods to change the original array (9):
1 2 3 4 5 |
|
For these methods that can change the original array, be careful to avoid changing the options of the original array during loop traversal , for example: changing the length of the array will cause problems with the length of the traversal.
pop() deletes the last element in an array
Definition: pop()
Method deletes the last element in an array element and returns this element.
Parameters: None.
1 2 3 |
|
shift() deletes the first element of the array
Definition: shift()
The method deletes the first element of the array and Return this element.
Parameters: None.
1 2 3 |
|
push() adds elements to the end of the array
Definition: push()
The method adds one or more elements to the end of the array element and returns the new length.
Parameters: item1, item2, …, itemX, the elements to be added to the end of the array
1 2 3 |
|
unshift()
Definition: unshift() Method adds one or more elements to the beginning of the array and returns the new length.
Parameters: item1, item2, …, itemX, the elements to be added to the beginning of the array
1 2 3 |
|
reverse() reverses the order of the elements in the array
Definition: reverse()
The method is used to reverse the order of elements in the array.
Parameters: None
1 2 3 |
|
splice() Add/delete array elements
Definition: splice()
Method to/ Add/remove items from the array and return the deleted item
Syntax: array.splice(index,howmany,item1,...,itemX)
Parameters:
index: required. An integer specifying the position at which to add/remove an item. Use a negative number to specify the position from the end of the array.
howmany: Required. The number of items to delete. If set to 0, items will not be deleted.
item1, …, itemX: Optional. New items added to the array.
Return value: If an element is deleted, a new array containing the deleted item is returned.
eg1: Delete element
1 2 3 4 5 6 |
|
eg2: Delete and add
1 2 3 4 5 6 7 8 |
|
eg3: Do not delete but only add:
1 2 3 4 5 6 |
|
从上述三个栗子可以得出:
数组如果元素不够,会删除到最后一个元素为止
操作的元素,包括开始的那个元素
可以添加很多个元素
添加是在开始的元素前面添加的
sort() 数组排序
定义: sort()
方法对数组元素进行排序,并返回这个数组。
参数可选: 规定排序顺序的比较函数。
默认情况下sort()
方法没有传比较函数的话,默认按字母升序,如果不是元素不是字符串的话,会调用toString()方法将元素转化为字符串的Unicode(万国码)位点,然后再比较字符。
1 2 3 4 5 6 |
|
比较函数的两个参数:
sort的比较函数有两个默认参数,要在函数中接收这两个参数,这两个参数是数组中两个要比较的元素,通常我们用 a 和 b 接收两个将要比较的元素:
若比较函数返回值<0,那么a将排到b的前面;
若比较函数返回值=0,那么a 和 b 相对位置不变;
若比较函数返回值>0,那么b 排在a 将的前面;
对于sort()方法更深层级的内部实现以及处理机制可以看一下这篇文章深入了解javascript的sort方法
sort排序常见用法:
1、数组元素为数字的升序、降序:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
2、数组多条件排序
1 2 3 4 5 6 7 8 9 |
|
3、自定义比较函数,天空才是你的极限
类似的:运用好返回值,我们可以写出任意符合自己需求的比较函数
1 2 3 4 5 6 7 8 9 |
|
ES6: copyWithin() 指定位置的成员复制到其他位置
定义: 在当前数组内部,将指定位置的成员复制到其他位置,并返回这个数组。
语法:
array.copyWithin(target, start = 0, end = this.length)
参数:
三个参数都是数值,如果不是,会自动转为数值.
target(必需):从该位置开始替换数据。如果为负值,表示倒数。
start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。
end(可选):到该位置前停止读取数据,默认等于数组长度。使用负数可从数组结尾处规定位置。
浏览器兼容(MDN): chrome 45,Edge 12,Firefox32,Opera 32,Safari 9, IE 不支持
eg:
1 2 3 4 5 6 7 |
|
从上述栗子:
第一个参数是开始被替换的元素位置
要替换数据的位置范围:从第二个参数是开始读取的元素,在第三个参数前面一个元素停止读取
数组的长度不会改变
读了几个元素就从开始被替换的地方替换几个元素
ES6: fill() 填充数组
定义: 使用给定值,填充一个数组。
参数:
第一个元素(必须): 要填充数组的值
第二个元素(可选): 填充的开始位置,默认值为0
第三个元素(可选):填充的结束位置,默认是为this.length
MDN浏览器兼容
1 2 3 4 |
|
不改变原数组的方法(8个):
ES5:
join、toLocateString、toStrigin、slice、cancat、indexOf、lastIndexOf、
ES7:
includes
join() 数组转字符串
定义: join()
方法用于把数组中的所有元素通过指定的分隔符进行分隔放入一个字符串,返回生成的字符串。
语法:
array.join(str)
参数:
str(可选): 指定要使用的分隔符,默认使用逗号作为分隔符。
1 2 3 |
|
使用join方法或者下文说到的toString方法时,当数组中的元素也是数组或者是对象时会出现什么情况?
1 2 3 4 5 |
|
所以,join()
/toString()
方法在数组元素是数组的时候,会将里面的数组也调用join()/toString(),如果是对象的话,对象会被转为[object Object]字符串。
toLocaleString() 数组转字符串
定义: 返回一个表示数组元素的字符串。该字符串由数组中的每个元素的 toLocaleString()
返回值经调用 join() 方法连接(由逗号隔开)组成。
语法:
array.toLocaleString()
参数:无。
1 2 |
|
如上述栗子:调用数组的toLocaleString
方法,数组中的每个元素都会调用自身的toLocaleString方法,对象调用对象的toLocaleString,Date调用Date的toLocaleString。
toString() 数组转字符串 不推荐
定义: toString()
方法可把数组转换为由逗号链接起来的字符串。
语法:
array.toString()
参数: 无。
该方法的效果和join方法一样,都是用于数组转字符串的,但是与join方法相比没有优势,也不能自定义字符串的分隔符,因此不推荐使用。
值得注意的是:当数组和字符串操作的时候,js 会调用这个方法将数组自动转换成字符串
1 2 |
|
slice() 浅拷贝数组的元素
定义: 方法返回一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组对象,且原数组不会被修改。
注意:字符串也有一个slice()
方法是用来提取字符串的,不要弄混了。
语法:
array.slice(begin, end);
参数:
begin(可选): 索引数值,接受负值,从该索引处开始提取原数组中的元素,默认值为0。
end(可选):索引数值(不包括),接受负值,在该索引处前结束提取原数组元素,默认值为数组末尾(包括最后一个元素)。
1 2 3 4 5 6 |
|
如上:新数组是浅拷贝的,元素是简单数据类型,改变之后不会互相干扰。
如果是复杂数据类型(对象,数组)的话,改变其中一个,另外一个也会改变。
1 2 3 4 5 6 7 |
|
原因在定义上面说过了的:slice()是浅拷贝,对于复杂的数据类型浅拷贝,拷贝的只是指向原数组的指针,所以无论改变原数组,还是浅拷贝的数组,都是改变原数组的数据。
cancat
定义: 方法用于合并两个或多个数组,返回一个新数组。
语法:
var newArr =oldArray.concat(arrayX,arrayX,......,arrayX)
参数:
arrayX(必须):该参数可以是具体的值,也可以是数组对象。可以是任意多个。
eg1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
ES6扩展运算符...合并数组:
因为ES6的语法更简洁易懂,所以现在合并数组我大部分采用...来处理,...运算符可以实现cancat的每个栗子,且更简洁和具有高度自定义数组元素位置的效果。
1 2 3 |
|
indexOf() 查找数组是否存在某个元素,返回下标
定义: 返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
语法:
array.indexOf(searchElement,fromIndex)
参数:
searchElement(必须):被查找的元素
fromIndex(可选):开始查找的位置(不能大于等于数组的长度,返回-1),接受负值,默认值为0。
严格相等的搜索:
数组的indexOf搜索跟字符串的indexOf不一样,数组的indexOf使用严格相等===搜索元素,即数组元素要完全匹配才能搜索成功。
注意:indexOf()不能识别NaN
eg:
1 2 3 4 |
|
使用场景:
数组去重
根据获取的数组下标执行操作,改变数组中的值等。
判断是否存在,执行操作。
lastIndexOf() 查找指定元素在数组中的最后一个位置
定义: 方法返回指定元素,在数组中的最后一个的索引,如果不存在则返回 -1。(从数组后面往前查找)
语法:
arr.lastIndexOf(searchElement,fromIndex)
参数:
searchElement(必须): 被查找的元素
fromIndex(可选): 逆向查找开始位置,默认值数组的长度-1,即查找整个数组。
关于fromIndex有三个规则:
正值。如果该值大于或等于数组的长度,则整个数组会被查找。
负值。将其视为从数组末尾向前的偏移。(比如-2,从数组最后第二个元素开始往前查找)
负值。其绝对值大于数组长度,则方法返回 -1,即数组不会被查找。
1 2 3 4 5 |
|
ES7 includes() 查找数组是否包含某个元素 返回布尔
定义: 返回一个布尔值,表示某个数组是否包含给定的值
语法:
array.includes(searchElement,fromIndex=0)
参数:
searchElement(必须):被查找的元素
fromIndex(可选):默认值为0,参数表示搜索的起始位置,接受负值。正值超过数组长度,数组不会被搜索,返回false。负值绝对值超过长数组度,重置从0开始搜索。
includes方法是为了弥补indexOf方法的缺陷而出现的:
indexOf方法不能识别NaN
indexOf方法检查是否包含某个值不够语义化,需要判断是否不等于-1,表达不够直观
eg:
1 2 3 4 5 |
|
兼容性(MDN): chrome47, Firefox 43,Edge 14,Opera 34, Safari 9,IE 未实现。
遍历方法(12个):
js中遍历数组并不会改变原始数组的方法总共有12个:
ES5:
forEach、every 、some、 fliter、map、reduce、reduceRight、
ES6:
find、findIndex、keys、values、entries
关于遍历:
关于遍历的效率,可以看一下这篇详解JS遍历
尽量不要在遍历的时候,修改后面要遍历的值
尽量不要在遍历的时候修改数组的长度(删除/添加)
forEach
定义: 按升序为数组中含有效值的每一项执行一次回调函数。
语法:
array.forEach(function(currentValue, index, arr), thisValue)
参数:
function(必须): 数组中每个元素需要调用的函数。
// 回调函数的参数
1. currentValue(必须),数组当前元素的值
2. index(可选), 当前元素的索引值
3. arr(可选),数组对象本身
hisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined
关于forEach()你要知道:
无法中途退出循环,只能用return退出本次回调,进行下一次回调。
它总是返回 undefined值,即使你return了一个值。
下面类似语法同样适用这些规则
1. 对于空数组是不会执行回调函数的
2. 对于已在迭代过程中删除的元素,或者空元素会跳过回调函数
3. 遍历次数再第一次循环前就会确定,再添加到数组中的元素不会被遍历。
4. 如果已经存在的值被改变,则传递给 callback 的值是遍历到他们那一刻的值。
eg:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
every 检测数组所有元素是否都符合判断条件
定义: 方法用于检测数组所有元素是否都符合函数定义的条件
语法:
array.every(function(currentValue, index, arr), thisValue)
参数:(这几个方法的参数,语法都类似)
function(必须): 数组中每个元素需要调用的函数。
// 回调函数的参数
1. currentValue(必须),数组当前元素的值
2. index(可选), 当前元素的索引值
3. arr(可选),数组对象本身
thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined
方法返回值规则:
如果数组中检测到有一个元素不满足,则整个表达式返回 false,且剩余的元素不会再进行检测。
如果所有元素都满足条件,则返回 true。=
eg:
1 2 3 4 5 6 7 8 |
|
some 数组中的是否有满足判断条件的元素
定义:数组中的是否有满足判断条件的元素
语法:
array.some(function(currentValue, index, arr), thisValue)
参数:(这几个方法的参数,语法都类似)
function(必须): 数组中每个元素需要调用的函数。
// 回调函数的参数
1. currentValue(必须),数组当前元素的值
2. index(可选), 当前元素的索引值
3. arr(可选),数组对象本身
thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined
方法返回值规则:
如果有一个元素满足条件,则表达式返回true, 剩余的元素不会再执行检测。
如果没有满足条件的元素,则返回false。
1 2 3 4 5 |
|
filter 过滤原始数组,返回新数组
定义: 返回一个新数组, 其包含通过所提供函数实现的测试的所有元素。
语法:
let new_array = arr.filter(function(currentValue, index, arr), thisArg)
参数:(这几个方法的参数,语法都类似)
function(必须): 数组中每个元素需要调用的函数。
// 回调函数的参数
1. currentValue(必须),数组当前元素的值
2. index(可选), 当前元素的索引值
3. arr(可选),数组对象本身
thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined
eg:
1 2 3 4 5 |
|
map 对数组中的每个元素进行处理,返回新的数组
定义:创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
语法:
let new_array = arr.map(function(currentValue, index, arr), thisArg)
参数:(这几个方法的参数,语法都类似)
function(必须): 数组中每个元素需要调用的函数。
// 回调函数的参数
1. currentValue(必须),数组当前元素的值
2. index(可选), 当前元素的索引值
3. arr(可选),数组对象本身
thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined
eg:
1 2 3 4 5 6 |
|
reduce 为数组提供累加器,合并为一个值
定义:reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,最终合并为一个值。
语法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数:
function(必须): 数组中每个元素需要调用的函数。
// 回调函数的参数
1. total(必须),初始值, 或者上一次调用回调返回的值
2. currentValue(必须),数组当前元素的值
3. index(可选), 当前元素的索引值
4. arr(可选),数组对象本身
initialValue(可选): 指定第一次回调 的第一个参数。
回调第一次执行时:
如果 initialValue 在调用 reduce 时被提供,那么第一个 total 将等于 initialValue,此时 currentValue 等于数组中的第一个值;
如果 initialValue 未被提供,那么 total 等于数组中的第一个值,currentValue 等于数组中的第二个值。此时如果数组为空,那么将抛出 TypeError。
如果数组仅有一个元素,并且没有提供 initialValue,或提供了 initialValue 但数组为空,那么回调不会被执行,数组的唯一值将被返回。
eg:
1 2 3 4 5 6 7 8 9 10 11 |
|
reduceRight 从右至左累加
这个方法除了与reduce执行方向相反外,其他完全与其一致,请参考上述 reduce 方法介绍。
ES6:find()& findIndex() 根据条件找到数组成员
find()定义:用于找出第一个符合条件的数组成员,并返回该成员,如果没有符合条件的成员,则返回undefined。
findIndex()定义:返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。
这两个方法
语法:
1 2 |
|
参数:(这几个方法的参数,语法都类似)
function(必须): 数组中每个元素需要调用的函数。
// 回调函数的参数
1. currentValue(必须),数组当前元素的值
2. index(可选), 当前元素的索引值
3. arr(可选),数组对象本身
thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined
这两个方法都可以识别NaN,弥补了indexOf的不足.
eg:
1 2 3 4 5 6 |
|
浏览器兼容(MDN):Chrome 45,Firefox 25,Opera 32, Safari 8, Edge yes,
ES6 keys()&values()&entries() 遍历键名、遍历键值、遍历键名+键值
定义:三个方法都返回一个新的 Array Iterator 对象,对象根据方法不同包含不同的值。
语法:
1 2 3 |
|
参数:无。
遍历栗子(摘自ECMAScript 6 入门):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
在for..of中如果遍历中途要退出,可以使用break退出循环。
如果不使用for...of循环,可以手动调用遍历器对象的next方法,进行遍历:
1 2 3 4 5 |
|
entries()浏览器兼容性(MDN):Chrome 38, Firefox 28,Opera 25,Safari 7.1
keys()浏览器兼容性(MDN):Chrome 38, Firefox 28,Opera 25,Safari 8,
注意:目前只有Safari 9支持,,其他浏览器未实现,babel转码器也还未实现
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
如何操作JS实现html中placeholder属性提示文字
The above is the detailed content of Summary of js array operations and parsing 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

WeChat is one of the mainstream chat tools. We can meet new friends, contact old friends and maintain the friendship between friends through WeChat. Just as there is no such thing as a banquet that never ends, disagreements will inevitably occur when people get along with each other. When a person extremely affects your mood, or you find that your views are inconsistent when you get along, and you can no longer communicate, then we may need to delete WeChat friends. How to delete WeChat friends? The first step to delete WeChat friends: tap [Address Book] on the main WeChat interface; the second step: click on the friend you want to delete and enter [Details]; the third step: click [...] in the upper right corner; Step 4: Click [Delete] below; Step 5: After understanding the page prompts, click [Delete Contact]; Warm

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.

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

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

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

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement
