Table of Contents
Traditional Array object methods
Modify the original array
Does not modify the original array
ES5 new Array
ES6数组方法
Home Web Front-end JS Tutorial What are the es6 array methods?

What are the es6 array methods?

Sep 10, 2021 pm 02:31 PM
es6 Array methods

es6 array methods include: "from()", "of()", "copyWithin()", "fill()", "find()", "findIndex()", "includes( )", "entries()", "keys()", "values()", etc.

What are the es6 array methods?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Traditional Array object methods

  • toSource() Returns the source code of the object.
  • toString() Converts an 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
##reverseindexOf(), lastIndexOf()spliceforEachcopyWithinmapfillfilter##entries(), keys(), values()

Modify the original array

  • push() adds one or more elements to the end of the array and returns the new length.
  • unshift() adds one or more elements to the beginning of the array and returns the new length.
  • pop() Removes and returns the last element of the array
  • shift() Removes and returns the first element of the array
  • sort() Sorts the elements of the array
  • reverse() Reverse the order of elements in the 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"
Copy after login

Does not modify the original array

  • concat() concatenates two or more arrays and returns the result.
  • join() puts all elements of the array into a string. Elements are separated by the specified delimiter.
  • slice() Returns selected elements 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"
Copy after login
Convert array-like objects (such as arguments) into real arrays
Array.prototype.slice.call(arguments);

ES5 new Array

  • Index method: indexOf(), lastIndexOf()
  • Iteration method: forEach(), map(), filter(), some(), every( )
  • Merge method: reduce(), reduceRight()
The method will not modify the original array

Index method

indexOf

array.indexOf(searchElement[, fromIndex])
Copy after login
  • 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号位开始搜索)
Copy after login

lastIndexOf

array.lastIndexOf(searchElement[, fromIndex])
Copy after login
  • 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 (未找到)
Copy after login
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 callback (callback function, required), the second parameter The first 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]);
Copy after login
  • 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
);

// 结果:
// 你好,张含韵
// 抱歉,江一燕,你不是本家人
// 抱歉,李小璐,你不是本家
Copy after login

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]);
Copy after login
var data = [1, 2, 3, 4];

var arrayOfSquares = data.map(function (item) {
  return item * item;
});

alert(arrayOfSquares); // 1, 4, 9, 16
Copy after login

filter

filter(), "filter", runs the given function on each item in the array and returns an array that meets the filter conditions.

array.filter(callback,[ thisObject]);
Copy after login
  • Filter’s callback function needs to return a Boolean value of true or false.
  • As long as the return value is weakly equal to == true/false, it does not have to return === 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]
Copy after login

every

every(), determines whether each item in the array meets the given conditions. When all items meet the conditions, it will return true.
Note: If the array is empty, true will be returned

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

some

#some() determines whether there are items in the array that meet the conditions. As long as one item meets the conditions, it will return true.
Note: If the array is empty, false will be returned

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

Merge method

这两个方法相比前面可能稍微复杂一些,它们都会迭代数组中的所有项,然后生成一个最终返回值。这两个方法接收两个参数。

  • 第一个参数callback,函数接受4个参数分别是(初始值total必选,当前值currentValue必选,索引值currentIndex可选,当前数组arr可选),函数需要返回一个值,这个值会在下一次迭代中作为初始值。
  • 第二个参数是迭代初始值(initialValue),参数可选,如果缺省,初始值为数组第一项,从数组第一个项开始叠加,缺省参数要比正常传值少一次运算。

reduce

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。 reduce() 对于空数组是不会执行回调函数的。

array. reduce(function(total, currentValue, currentIndex, array) {<br/> // ...<br/>});

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

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

Array方法

isArray

判断参数是否是”Array”返回true或false。

var a = [1,2,3];
Array.isArray(a);   //true
Copy after login

ES6数组方法

Array方法

Array.from()

用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。

let arrayLike = {
    &#39;0&#39;: &#39;a&#39;,
    &#39;1&#39;: &#39;b&#39;,
    &#39;2&#39;: &#39;c&#39;,
    length: 3
};

let arr2 = Array.from(arrayLike); // [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
Copy after login

Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。

Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]
Copy after login

Array.of()

用于将一组值,转换为数组。

Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Copy after login

实例方法

会改变原数组

  • copyWithin()

在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。

array. copyWithin(target, start = 0, end = this.length);
Copy after login
  • target(必需):从该位置开始替换数据。如果为负值,表示倒数。
  • start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。
  • end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]
Copy after login
  • fill()

使用给定值,填充一个数组。

[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;].fill(7);   // [7, 7, 7]

let arr = new Array(3).fill([]);
arr[0].push(5);       // [[5], [5], [5]]
Copy after login

不会改变原数组

  • find()

用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。
find方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。

[1, 4, -5, 10].find((n) => n < 0)
// -5
[1, 5, 10, 15].find(function(value, index, arr) {
  return value > 9;
}) // 10
Copy after login
  • findIndex()

findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2
Copy after login
  • includes()

返回一个布尔值,表示某个数组是否包含给定的值。

[1, 2, 3].includes(2) // true
Copy after login
  • entries(),keys() 和 values()

ES6提供了三个新方法:entries()、keys()和values(),用来遍历数组。它们都返回一个遍历器对象,可以用for...of循环进行遍历,唯一的区别是keys()是对数组的键名的遍历、values()是对数组键值的遍历,entries()方法是对数值的键值对的遍历。

for (let index of [&#39;a&#39;, &#39;b&#39;].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of [&#39;a&#39;, &#39;b&#39;].values()) {
  console.log(elem);
}
// &#39;a&#39;
// &#39;b&#39;

for (let [index, elem] of [&#39;a&#39;, &#39;b&#39;].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"
Copy after login

如果不使用for...of循环,可以手动调用遍历器对象的next方法,进行遍历。

let letter = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];
let entries = letter.entries();
console.log(entries.next().value); // [0, &#39;a&#39;]
console.log(entries.next().value); // [1, &#39;b&#39;]
console.log(entries.next().value); // [2, &#39;c&#39;]
Copy after login

【推荐学习:javascript高级教程

Modify the original array Do not modify the original array
push, pop concat
unshift, shift join
sort slice
##some
every
reduce,reduceRight
includes
finde, findIndex

The above is the detailed content of What are the es6 array methods?. 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
4 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)

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

How to reverse an array in ES6 How to reverse an array in ES6 Oct 26, 2022 pm 06:19 PM

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

Is require an es6 syntax? Is require an es6 syntax? Oct 21, 2022 pm 04:09 PM

No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

Is es6 map ordered? Is es6 map ordered? Nov 03, 2022 pm 07:05 PM

The map is ordered. The map type in ES6 is an ordered list that stores many key-value pairs. The key names and corresponding values ​​support all data types; the equivalence of key names is determined by calling the "Objext.is()" method. Implemented, so the number 5 and the string "5" will be judged as two types, and can appear in the program as two independent keys.

Is es2015 the same as es6? Is es2015 the same as es6? Oct 25, 2022 pm 06:51 PM

es2015 is es6. The full name of es is "ECMAScript", which is a universal scripting language implemented according to the ECMA-262 standard. The version officially released in June 2015 is officially called ECMAScript2015 (ES2015). Because it is the 6th version of ECMAScript, it can Referred to as es6.

See all articles