Home  >  Article  >  Web Front-end  >  Summary of JavaScript array methods

Summary of JavaScript array methods

大家讲道理
大家讲道理Original
2017-01-23 11:10:541376browse

Arrays in JavaScript are very special. Unlike C or Java, which have a whole set of arrays and lists, arrays in JS can be used as a stack or queue. Four Big operations pop, push, shift, unshift.

For an array method, there are two issues that we are most concerned about. What is the return value and whether it will affect the original array , typical examples are the splice and slice methods. For functions that return the original array, we can chain calls directly to the array, which is pretty cool (array.filter().sort().reverse()).

I would like to summarize the array method of Array with these two questions.

Array

Array.length is the length of the array. Each newly created array object will have a length object. The prototype can be modified through Array.prototype, but the basic use and operation of arrays are not what they are today. Focus, let's look at the array method.

Generally, array methods will have a thisArg parameter at the end, which will specify the internal this pointer. If there is a fallback function in the parameters, this fallback function generally accepts three parameters, value, index and array, which respectively represent the currently passed in value, the index where the currently passed in value is located and the current processed array.

Directory index:

concat

This method can be used to splice arrays. The parameter is one or more arrays, and the returned result is a spliced ​​array.

The concat method will create a new array, and then call it with the elements in the object (the object pointed to by this, the original array) and the elements in the array type parameters of all parameters and non-array types. The parameters themselves are put into this new array in order, and that array is returned. The concat method does not modify the original array and parameter array, and has the same effect on non-array objects.

  1. Return the spliced ​​new array;

  2. Do not modify the original array and parameter array;

  3. Parameters can be non-arrays.

var a1 = [1, 2, 3],
  a2 = [4, 5, 6],
  a3 = [7, 8, 9];
var newarr = a1.concat(a2, a3);
newarr //[1, 2, 3, 4, 5, 6, 7, 8, 9]
a1 //[1, 2, 3]
newarr = a1.concat(4, a3);//[1, 2, 3, 4, 7, 8, 9]
newarr = a1.concat('hello');//[1, 2, 3, "hello"]
##every

every() method test array Whether all elements of have passed the test of the specified function.

arr.every(callback) will execute the callback method on each element until callback returns false. Sometimes the every method is compared with the forEach method, because forEach cannot be stopped, but the every method can stop midway when it returns flase.

  1. If all tests pass, the function returns the value true. If it exits halfway, it returns false;

  2. will not affect the original array.

##
function isBigEnough(element, index, array) {
  console.log(index);
  return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// 0
// 1
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// 0 1 2 3 4
// passed is true
##filter
filter() method uses the specified The function tests all elements and creates a new array containing all elements that pass the test.

In fact, this method is a filtering method. The previous every method only judges and does not filter. The filter will filter out some that do not meet the conditions and return a new array.

Returns a new array that meets the filtering conditions;
  1. will not change the original array.
function isBigEnough(element, index, array) {
  return (element >= 10);
}
var a1 = [19, 22, 6, 2, 44];
var a2 = a1.filter(isBigEnough);
a1 //[19, 22, 6, 2, 44]
a2 //[19, 22, 44]
##forEachforEach() method for array The provided function (callback function) is executed once for each element.

The function has no return value, that is, underfined;

  1. has no effect on the original array.

  2. ##
    function logArrayElements(element, index, array) {
        console.log("a[" + index + "] = " + element);
    }
    
    // 注意索引2被跳过了,因为在数组的这个位置没有项
    var result = [2, 5, 9].forEach(logArrayElements);
    // a[0] = 2
    // a[1] = 5
    // a[2] = 9
    result //underfined
##indexOfindexOf() method returns to The specified element can be found at the first index value found in the array, otherwise -1 is returned.

The return value is the index value of the found element or -1;

    does not affect the original array.
  1. var array = [1, 2, 5];
    array.indexOf(5); // 2
    array.indexOf(7); // -1
  2. join
  3. The join() method joins all the elements in the array into a string.

  4. In fact, the first thing that comes to mind for join is the split operation of strings. These two are often used together to process strings.

Returns the concatenated string;

    does not affect the original array.
  1. var a1 = [1, 2, 3];
    var a2 = a1.join();
    a1 //[1, 2, 3]
    a2 //"1,2,3"
    a2 = a1.join("");//"123"
    a2 = a1.join("-");//"1-2-3"
##lastIndexOfIn fact, this is a replica of indexOf.
lastIndexOf() method returns the specified The index of the last element (that is, a valid JavaScript value or variable) in the array, or -1 if it does not exist. Search forward from the back of the array, starting from fromIndex.

Returns the index of the first element found;

has no effect on the original array.
  1. var array = [2, 5, 9, 2];
    var index = array.lastIndexOf(2);
    // index is 3
    index = array.lastIndexOf(7);
    // index is -1
    index = array.lastIndexOf(2, 3);
    // index is 3
    index = array.lastIndexOf(2, 2);

map

map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。 

map reduce 这两个函数在处理数组上一直都是一把手,带来很大的便捷性。

  1. 返回一个经过回掉函数处理的新数组;

  2. 不对原数组产生影响。

var a1 = [1, 4, 9];
var a2 = a1.map(Math.sqrt);
a1 //[1, 4, 9]
a2 //[1, 2, 3]

reduce

reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始合并,最终为一个值。 

reduce 是一个合并的过程,从左到右,直到把所有元素合并到一起,并返回最终的结果。它接受两个参数,第一个参数是一个回掉函数,第二个参数是一个初始值,表示处理第一个元素时的前一个值。这个回掉函数接受四个参数,依次是 accumulator(上次处理的结果),currentValue(当前元素的值),index(当前元素索引),array(调用 reduce 的数组)。

  1. 返回最终合并的结果,即回掉函数的输出,可以为字符串,对象,数组等任意结果;

  2. 不对原数组产生影响。

var getAdd = (pre, cur) => pre + cur;
var a1 = [1, 2, 3];
var a2 = a1.reduce(getAdd, 0);
a1 //[1, 2, 3]
a2 //6

reduceRight

reduceRight() 方法接受一个函数作为累加器(accumulator),让每个值(从右到左,亦即从尾到头)缩减为一个值。(与 reduce() 的执行方向相反)

var toStr = (pre, cur) => '' + pre + cur;
var a1 = [1, 2, 3];
var a2 = a1.reduce(toStr, '');
a2 //"123"
a2 = a1.reduceRight(toStr, '');
a2 //"321"

push

push() 方法添加一个或多个元素到数组的末尾,并返回数组新的长度(length 属性值)。

如果把数组当作栈,push pop 操作是栈进和出,而往往很多人会忽略函数执行后的返回值。

  1. 返回 push 操作执行之后数组的长度;

  2. 肯定改变。

var a1 = [1, 2, 3];
var a2 = a1.push(4);
a1 //[1, 2, 3, 4]
a2 //4

pop

pop() 方法删除一个数组中的最后的一个元素,并且返回这个元素。 

  1. 返回删除的这个元素;

  2. 肯定改变。

var a1 = [1, 2, 3];
var a2 = a1.pop();
a1 //[1, 2]
a2 //3

unshift

unshift() 方法在数组的开头添加一个或者多个元素,并返回数组新的 length 值。

  1. 返回 length 值;

  2. 肯定改变。

var a1 = [1, 2, 3];
var a2 = a1.unshift(4);
a1 //[4, 1, 2, 3]
a2 //4

shift

shift() 方法删除数组的 第一个 元素,并返回这个元素。该方法会改变数组的长度。 

shift 方法和 push 方法可以组成一个队列的操作啦。

  1. 返回删除的这个元素;

  2. 肯定改变。

reverse

reverse() 方法颠倒数组中元素的位置。第一个元素会成为最后一个,最后一个会成为第一个。 

  1. 函数返回值是修改了的原数组;

  2. 原数组会修改。

var a1 = [1, 2, 3];
var a2 = a1.reverse();
a1 //[3, 2, 1]
a1 === a2; //true

slice

slice() 方法会浅复制(shallow copy)数组的一部分到一个新的数组,并返回这个新数组。 

slice 的参数包括拷贝的初识位置,结束位置(左闭右开),与 splice 有区别。由于不会改变原数组,这个数组可以用于前拷贝,比如经常看别人使用: arr.slice(0) ,表示拷贝数组。

  1. 返回浅拷贝后的新数组;

  2. 不会改变原数组。

var a1 = [1, 2, 3, 4, 5];
var a2 = a1.slice(1, 3);
a1 //[1, 2, 3, 4, 5]
a2 //[2, 3]

splice

splice() 方法用新元素替换旧元素,以此修改数组的内容。 

如其名,分割,会修改原数组的内容,返回一个新数组,而且它的参数也比较多,第一个参数表示初始位置,第二个参数表示分割长度,第三个参数及以后表示分割后在分割处添加新元素。

  1. 返回分割的元素组成的数组;

  2. 会对数组进行修改,原数组会减去分割数组。

var a1 = [1, 2, 3, 4];
var a2 = a1.splice(1, 2);
a1 //[1, 4]
a2 //[2, 3]
a1 = [1, 2, 3, 4];
a2 = a1.splice(1, 2, 5, 6);
a1 //[1, 5, 6, 4]

some

some() 方法测试数组中的某些元素是否通过了指定函数的测试。 

sort

sort() 方法对数组的元素做原地的排序,并返回这个数组。 sort 排序可能是不稳定的。默认按照字符串的Unicode码位点(code point)排序。 

sort 函数用于排序,比较常用,若没有制定排序函数,则按照 unicode 位点进行排序,而且数字会被转成字符串,所以 ‘123’ 要排在 ‘11’ 的后面。

我们会用 sort 做一些有意思的排序,比如汉字按照拼音排序。

  1. 返回排序后的原数组;

  2. 会对数组进行修改。

var big = function(a, b){
  return a - b;
}
var a1 = [2, 4, 77, 1];
var a2 = a1.sort(big);
a1 //[1, 2, 4, 77]
a1 === a2; //true

localeCompare 可以对汉字进行排序,当同时出现汉字和字母的时候会有 bug:

var sort_py = function(a, b){
  return a.localeCompare(b);
}
var a1 = ["北京", "上海", "南京", "合肥"];
a1.sort(sort_py);
//["北京", "合肥", "南京", "上海"]

toString

toString() 返回一个字符串,表示指定的数组及其元素。 

显然,这个方法和 join 方法比较一下。

  1. 返回拼接的字符串;

  2. 不会改变原数组。

var a1 = [1, 2, 3];
var a2 = a1.toString();
a2 //"1,2,3"

ES6 中新添的数组方法

上面的这些方法都是 ES5 的,来看看 ES6 添加了哪些新方法。

copyWithin

copyWithin() 方法会浅拷贝数组的部分元素到同一数组的不同位置,且不改变数组的大小,返回该数组。 

接受三个参数,分别是要拷贝到的位置 target,拷贝开始位置 start 和结束位置 end。

  1. 返回修改了的原数组;

  2. 会对数组进行修改,且是浅拷贝;

  3. 参数可负,负值时倒推,且 end 为空表示数组长度。

var a1 = [1, 2, 3, 4, 5];
var a2 = a1.copyWithin(0, 2, 4);
a1 //[3, 4, 3, 4, 5]
a2 //[3, 4, 3, 4, 5]
a1 === a2; //true

find

如果数组中某个元素满足测试条件,find() 方法就会返回满足条件的第一个元素,如果没有满足条件的元素,则返回 undefined。 MDN array.find

  1. 返回找到的那个元素,若未找到,返回 underfined

  2. 不对原数组产生影响。

function isBigEnough(element, index, array) {
  return (element >= 10);
}
var a1 = [8, 18, 14];
var num = a1.find(isBigEnough); //18

findIndex

findIndex()方法用来查找数组中某指定元素的索引, 如果找不到指定的元素, 则返回 -1。 

这个方法可以参考 find 方法,只是返回值是元素的索引而非元素本身。

fill

使用 fill() 方法,可以将一个数组中指定区间的所有元素的值, 都替换成或者说填充成为某个固定的值。 

fill 方法接受三个参数,第一个参数 value 表示要填充到值,后面两个 start 和 end 表示开始和结束位置,可选,且左闭右开。

  1. 函数返回值是修改了的原数组;

  2. 可对数组产生影响。

var a1 = [1, 2, 3, 4, 5];
var a2 = a1.fill(6, 1, 4);
a1 //[1, 6, 6, 6, 5]
a2 //[1, 6, 6, 6, 5]
a1 === a2; //true

keys

数组的 keys() 方法返回一个数组索引的迭代器。 

这个方法会返回一个数组索引的迭代器,迭代器在 ES6 中有特殊的用途。

  1. 函数返回一个迭代器对象;

  2. 不会改变原数组。

var arr = ["a", "b", "c"];
var iterator = arr.keys();

console.log(iterator.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

entries

entries() 方法返回一个 Array Iterator 对象,该对象包含数组中每一个索引的键值对。 

var arr = ["a", "b", "c"];
var eArr = arr.entries();

console.log(eArr.next().value); // [0, "a"]
console.log(eArr.next().value); // [1, "b"]
console.log(eArr.next().value); // [2, "c"]

includes

includes() 方法用来判断当前数组是否包含某指定的值,如果是,则返回 true,否则返回 false。 

该函数接受两个参数,第二个参数表示开始查找位置,起始位置为 0。这个方法与 indexOf 方法最大的区别不仅在于返回值一个是索引,一个是布尔值,indexOf 方法使用的是 === 来判断,无法判断 NaN 情况,而 includes 可以判断。

  1. 返回 true 或 false;

  2. 不会改变原数组。

var a1 = [1, NaN];
a1.indexOf(NaN);//-1
a1.includes(NaN);//true

 

Statement:
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