Table of Contents
some
every
join
push / pop
unshift / shift
sort(fn) / reverse
splice
concat
slice
indexOf / lastIndexOf(value, fromIndex)
reduce / reduceRight
isArray *
ES6
find *
findIndex *
from *
entries *
keys *
values
includes *
copyWithin
of
fill
遍历
数组
for
for...in
for...of
对象【属性】
Object.keys(obj)
Object.getOwnPropertyNames(obj)
Object.getOwnPropertySymbols(obj)
Reflect.ownKeys(obj)
Home Web Front-end JS Tutorial Summary of common API methods and traversal methods for JavaScript arrays (with examples)

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

Apr 11, 2019 am 10:36 AM
ecmascript javascript

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!

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

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

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles