Home > Web Front-end > JS Tutorial > body text

Summary of common API methods and traversal methods for JavaScript arrays (with examples)

不言
Release: 2019-04-11 10:36:00
forward
2127 people have browsed it

This article brings you a summary of common API methods and traversal methods for JavaScript arrays (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Array(array)

ES5 *

map

Syntax: [].map(function(item, index, array) {return xxx} )
Function: Traverse the array and return a new array composed of the callback return value. The original array will not be changed, and the empty array will not be detected.

forEach

Syntax: [].forEach( function(item, index, array) {})
Function: Unable to break, you can use throw new Error in try/catch to stop without changing the original array

filter

Syntax: [].filter(function(item, index, array) {})
Function: filter, return the filtered array, do not change the original array, and will not detect empty arrays

eg:

const data = [-8, 9, 5, 3];
const res = data.filter(function(item) {
    if (item > 3) {
      return item
    }
});
console.log(res); // [9, 5]
Copy after login

some

Grammar: [].some(function(item, index, array) {})
Function: If one item returns true, then the whole true, Does not change the original array

every

Syntax: [].every(function(item, index, array) {})
Function: All conditions must be met to return true. If one item returns false, the whole is false. Does not change the original array

join

Syntax: [].join(str)
Function: Returns the array concatenated into a string by specifying the connector str, does not change the original array

push / pop

Syntax: [].push(item) / [].pop(item)
Function: push push and pop pop at the end of the array, return the length/pop-up item of the changed array, Change the original array

unshift / shift

Syntax: [].unshift(item) / [].shift(item)
Function: Push unshift and pop-up shift at the head of the array, return the length of the changed array/pop-out item, Change the original array

sort(fn) / reverse

Syntax :[].sort(fn) [].reverse()
Function: Sort and reverse according to rules, Change the original array

splice

Syntax: [].splice(start, number, value1, value2...)
Function: Return an array composed of deleted elements, starting from start Delete number values ​​and insert valueN parameter list into the array. Change the original array

concat

Syntax: [].concat([])
Function: Connect n (n >= 2) arrays, return a copy of the array after the array connection, shallow copy, does not change the original array

slice

Syntax: [].slice(start, end)
Function: Return the truncated new array, Does not change the original array

indexOf / lastIndexOf(value, fromIndex)

Syntax: [].indexOf(value[, fromIndex])
Function:
Find array item
indexOf starting from fromIndex (default is 0) and looking backwards value
lastIndexOf starting from fromIndex (default is -1) Search forwardvalue
Return the subscript corresponding to value

reduce / reduceRight

Syntax: reduce / reduceRight(callback[, initialValue])
Function: Execute in pairs, prev is the return value of the last simplified function, cur is the current value (starting from the second item)
Parameters of the callback function: previous value (previousValue), current value ( currentValue), the index value (currentIndex) and the array itself (array)
initialValue optional initial value, as the value passed to previousValue when the callback function is first called. That is, pass in the starting value (additional bonus) for operations such as accumulation

reduceRight starts from the end of the array

isArray *

Syntax: Array.isArray(value)
Function: Used to determine whether the parameter value is an Array

ES6

find *

ind(fn)`
Function: Return the first array element that meets the conditions item

findIndex *

Syntax: [].findIndex(fn)
Function: Return the index of the first array element that meets the conditions

from *

Syntax: [].fill(value[, start, end])
Function: Convert array-like objects and traversable (iterable) objects into real arrays
Commonly used:

const set = new Set(3, 8, 9, 0)
Array.from(set)
Copy after login

entries *

Syntax: [].entries()
Function: Return iterator: Return key-value pair

[Note]Object.entries(obj) The method returns an array of key-value pairs for the given object's own enumerable properties, arranged in the same order as returned when using a for...in loop to traverse the object (the difference is that the for-in loop also enumerates the prototype chain Attributes in) [MDN]
And [].entries() is a method on Array.prototype
keys/values ​​similar to

//数组
const arr = ['a', 'b', 'c'];
for(let v of arr.entries()) {
    console.log(v)
}
// [0, 'a'] [1, 'b'] [2, 'c']

//Set
const arr1 = new Set(['a', 'b', 'c']);
for(let v of arr1.entries()) {
    console.log(v)
}
// ['a', 'a'] ['b', 'b'] ['c', 'c']

//Map
const arr2 = new Map();
arr2.set('a', 'a');
arr2.set('b', 'b');
for(let v of arr2.entries()) {
    console.log(v)
}
// ['a', 'a'] ['b', 'b']
Copy after login

keys *

Syntax: [].keys()
Function: Return iterator: Return key key (i.e., the first value in each array above)

values

Syntax: [].values()
Function: Return iterator: return value value (that is, the second value in each array above)

includes *

语法:[].includes(val[, fromIndex])
功能:用于从fromIndex判断数组中是否包含val,可替代ES5中的 indexOf

copyWithin

语法:[].copyWithin(target[, start[, end]])
功能:浅复制数组的一部分(start~end)到同一数组中的另目标位置target,返回改变后的数组,而不修改其大小;start默认为0, end默认为length-1; 改变原数组

of

语法:Array.of()
功能:创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型

Array构造函数 & Array.of() 区别
实例说明

Array.of(7);       // [7] 
Array.of(1, 2, 3); // [1, 2, 3]

Array(7);          // [ , , , , , , ]
Array(1, 2, 3);    // [1, 2, 3]
Copy after login

fill

语法:[].fill(value[, start, end])
功能:用指定的元素填充数组,可用于初始化数组,返回改变后的数组,改变原数组
填充值(value),填充起始位置(start,默认为0),填充结束位置(end,默认为数组length)。

遍历

数组

map/forEach/some/every/filter 见上

for

for...in

遍历所有可枚举属性,常用于遍历对象Object

for...of

遍历所有可迭代iterable的对象

对象【属性】

for...in

循环遍历对象自身的和继承的可枚举属性(不含Symbol属性)【可枚举 - Symbol】

Object.keys(obj)

返回一个数组,包括对象自身的(不含继承的)所有可枚举属性(不含Symbol属性)【自身可枚举 - Symbol】

Object.getOwnPropertyNames(obj)

返回一个数组,包含对象自身的所有属性(不含Symbol属性,但是包括不可枚举属性)【自身 - Symbol】

Object.getOwnPropertySymbols(obj)

返回一个数组,包含对象自身的所有Symbol属性【自身的Symbol】

Reflect.ownKeys(obj)

返回一个数组,包含对象自身的所有属性,不管是属性名是Symbol或字符串,也不管是否可枚举  【自身所有】

【相关推荐:JavaScript视频教程

The above is the detailed content of Summary of common API methods and traversal methods for JavaScript arrays (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!