Home > Web Front-end > JS Tutorial > Summary of ES5 and ES6 array methods

Summary of ES5 and ES6 array methods

不言
Release: 2018-03-31 09:48:51
Original
1948 people have browsed it

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

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"
Copy after login
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])
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 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]);
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(),“过滤”,对数组中的每一项运行给定函数,返回满足过滤条件组成的数组。

array.filter(callback,[ thisObject]);
Copy after login
  • 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]
Copy after login

every

every(),判断数组中每一项都是否满足所给条件,当所有项都满足条件,才会返回true。

array.every(callback,[ thisObject]);
Copy after login
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(),判断数组中是否存在满足条件的项,只要有一项满足条件,就会返回true。

array.some(callback,[ thisObject]);
Copy after login
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

归并方法

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

  • 第一个参数callback,函数接受4个参数分别是(初始值total必选,当前值currentValue必选,索引值currentIndex可选,当前数组arr可选),函数需要返回一个值,这个值会在下一次迭代中作为初始值。

  • 第二个参数是迭代初始值(initialValue),参数可选,如果缺省,初始值为数组第一项,从数组第一个项开始叠加,缺省参数要比正常传值少一次运算。

reduce

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

array. reduce(function(total, currentValue, currentIndex, array) {
    // ...
});
Copy after login
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]);
Copy after login
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

相关推荐:

ES6系列之声明变量let与const

Es6数组的扩展

ES5实例详解javascript多种继承方式


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!

Related labels:
source:php.cn
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