js Array Array detailed operation method and analytical Collection

First, create an array:

1, create a literal way
 There are a = [3,11,18]; // [3,11,18]
 
2, the configuration of add
 var a=new Array(); //[]
 var b=new  Array(3)//[, , , ]
 var a =new  Array(3,11,8); // [ 3,11,8 ] ;

3, ES6 Array.of () returns an array of all the parameter values ​​consisting of

Definition: Returns an array composed of all the parameter values, if there is no argument, return an empty array.

Purpose: The purpose Array.of () appears to solve the above-described configuration is due to the behavior of the number of different parameters, there is a difference resulting in a problem.

        let a = Array.of(3, 11, 8); // [3,11,8]

        let a = Array.of(3); // [3]

        let a = Array.of(); // [ ]

4, ES6 Arrary.from () will be two types of objects into a real array

Definition: for the two types of objects into a true array (do not change the original object and returns a new array).

  The first parameter (must): to be converted into real objects array;

      The second parameter (optional): map a procedure similar array, each processing element, the value of the processed returned into the new array;

      The third parameter (optional): for this binding

      example:

    // 1. Object has a length property

                 let obj = {0: 'a', 1: 'b', 2:'c', length: 3};

     // 2. Deploy the data structure Iterator interface such as: string, Set, NodeList objects

       let arr = Array.from('hello'); // ['h','e','l','l','o']

                 let arr = Array.from(new Set(['a','b'])); // ['a','b']

Second, the array method:

Array methods can be divided into three categories: 1, changing the values ​​of the original array

           2, does not change the value of the original array

                                 3, the array traversal methods

1, a method of changing the value of the original array:

let a=[1,2,3] 

es5: a.splice()/a.sort()/a.pop()/a.shift()   a.push()/a.unshift()/a.reverse()

es6:a.copyWithin()/a.fill

Note: For can alter the original array method, pay attention to changes in the original array in the cycle options, such as: changing the length of the original array, causing problems when traversing length.

1 "splice (): Add Remove array elements

Definitions: splice () to add or delete an array of items to array, return item to be deleted

 array.splice(index,howmany,item1,item2,item3,.......itemX)

   1, index: Required. Integer, regulations add / remove items of location, may require the use of a negative position from the end of the array.

   2, howmany: Optional. The number of items to delete. If set to 0, it will not remove items.

   3, item1, ..., itemX: Optional. New projects added to the array.

Return Value: If there is an element is deleted, the return is to include elements of the new array is deleted

eg1: Removing elements

  let a = [1, 2, 3, 4, 5, 6, 7];

      let item=a.splice(0,3)  //[1,2,3]

      console.log(a) //[4,5,6,7]

  // start from the array subscript 0, delete the three elements

  let item = a.splice(-1, 3); // [7]

  // start removing elements from three last element, because the last element, so only 7 deleted

eg2: delete and add

  let a = [1, 2, 3, 4, 5, 6, 7];

  let item = a.splice (0,3, 'add'); // [1,2,3] let item = a.splice (0,3, 'add'); // [1,2,3]

  console.log (a); // [ 'add', 4,5,6,7]

  // start from the array subscript 0, delete the three elements, and add elements 'Add'

  let b = [1, 2, 3, 4, 5, 6, 7];

  let item = b.splice (-2,3, 'add 1', 'Add 2'); // [6,7]

  console.log (b); // [1,2,3,4,5, 'add 1', 'Add 2']

  // starting from the last element of the second array, delete the three elements, and add two elements 'add 1', 'Add 2'

eg3: do not delete only add

  let a = [1, 2, 3, 4, 5, 6, 7];

  let item = a.splice (0,0, 'add 1', 'Add 2'); // [] element is not deleted, return an empty array

  console.log (a); // [ 'add 1', 'Add 2', 1,2,3,4,5,6,7]

  let b = [1, 2, 3, 4, 5, 6, 7];

  let item = b.splice (-1,0, 'add 1', 'Add 2'); // [] element is not deleted, return an empty array

  console.log (b); // [1,2,3,4,5,6, 'add 1', 'Add 2', 7] is added in front of the two elements of the last element

splice Summary: 1, if the array element is not enough, it will be deleted until the last element;

      2, the elements of the operation, including the start of that element

      3, Add to add a lot of elements

      4, is added to start before the element added

Array after the array is sorted, and returns the sort: 2 "sort ()

Optional parameters: a predetermined comparison function of the sort order

By default, Sort () function when the comparison did not pass, the default alphabetical ascending, if the element is not a string, then the method calls toString site elements into unicode string, and then comparison is performed.

  var a = ["Banana", "Orange", "Apple", "Mango"];

  a.sort(); // ["Apple","Banana","Mango","Orange"];

  // sort of digital time because after conversion to Unicode strings, some numbers would be more of the General Assembly at the back which is obviously not what we want

  There are a = [10, 1, 3, 20,25,8];

  console.log(a.sort()) // [1,10,20,25,3,8];

Compare function of two arguments:

sort comparison function has two default parameters, to receive these two parameters in the function, the two parameters are two arrays of elements to be compared, we typically receives two elements to be compared with a and b:

  • If the comparison function returns the value <0, then discharged to a front of b;
  • If the comparison function returns the value = 0, a and b are the same relative position;
  • If the comparison function returns a value> 0, then b is the row in front of a;

For the sort () method to achieve a deeper level of internal and handling mechanisms can look at the article in-depth understanding of the sort method javascript

sort sort common usage:

var array = [10, 1, 3, 4,20,4,25,8]; // ab <0; a b of the front row, according to the size of a sort; for example a is 10, b is 20, ab <0; a row in front of the B;

array.sort(function(a,b){

return a-b

});//console.log(array);array=[1,3,4,4,8,10,20,25]

EG1: digital array elements in ascending, descending order:

Array = var [10,. 1,. 3, 4,20,4,25,8];
// ascending ab <0 a to b is discharged to the front, according to the size of a sort
@ a is such minuend 10, 2010-20 minuend <0 minuend A (10) on subtraction b (20) in front of
Array.sort (function (A, B) {
return ab &;
});
the console.log (Array); // [1,3,4,4,8,10,20,25];
// descending minuend and subtrahend swapped 20-10> 0 minuend b (20) on subtraction a (10) front
Array.sort (function (a, B) {
return BA;
});
the console.log (Array); // [25,20,10,8,4,4,3,1];

eg2: an array of multi-criteria Sort by:

var array = [{id: 10 , age: 2}, {id: 5, age: 4}, {id: 6, age: 10}, {id: 9, age: 6}, {id: 2, age :. 8}, {id: 10, age:}. 9]; 
     Array.sort (function (a, B) { 
         IF (a.id === b.id) {// If the id values are equal, according to age of in descending 
             return b.age - a.age 
         } id the else {// If the values are not equal, in ascending order according to the value of the id 
             return a.id - b.id 
         } 
     }) 
  // [{ "id": 2, "Age ": 8}, {" id ": 5," age ": 4}, {" id ": 6," age ": 10}, {" id ": 9," age ": 6}, {" id ": 10," age ": 9}, {" id ": 10," age ": 2}]

eg3: custom comparison function:

    var array = [{name: ' Koro1'}, {name: 'Koro1'}, {name: 'OB'}, {name: 'Koro1'}, {name: 'OB'}, {name: 'OB' }]; 
    Array.sort (function (a, b) { 
        IF (a.name === 'Koro1') {// if name is 'Koro1' returns -1, -1 <0 a b row in front of the 
            return -1 
        } the else {// If not, a b row behind the 
          return. 1 
        } 
    }) 
    // [{ "name": "Koro1"}, { "name": "Koro1"}, { "name": "Koro1"}, { "name ": "OB"}, { "name": "OB"}, { "name": "OB"}]

3 "pop (): delete the last element of an array

Definitions: pop () Removes the last element of an array and returns that element

Parameters: None

    let  a =  [1,2,3];
    let item = a.pop();  // 3
    console.log(a); // [1,2]

  

4 "() shift: Removes the first element of the array

Definitions: shift () method removes the first element of the array and returns that element.

Parameters: None

    let  a =  [1,2,3];
    let item = a.shift();  // 1
    console.log(a); // [2,3]

  

5 "push (): add elements to the end of an array

Definitions: push () method to add one or more elements to the end of the array, and returns the new length.

Parameters: item1, item2, ..., itemX, to add to the end of the array elements

    A = the let [l, 2,3]; 
    the let a.push Item = ( 'end'); //. 4 
    the console.log (A); // [l, 2,3, 'end']

6 "unshift (): add elements to the end of an array

Definitions: unshift () method to add one or more elements to the beginning of the array, and returns the new length.

Parameters: item1, item2, ..., itemX, to add to the beginning of the array elements

    A = the let [l, 2,3]; 
    the let a.unshift Item = ( 'beginning'); // 4 
    [ 'beginning', 1,2,3] //; console.log ( a)

Reversing the order of elements in the array: 7 "reverse ()

Definitions: reverse () method to reverse the order of elements in the array.

Parameters: None

    let  a =  [1,2,3];
    a.reverse();  
    console.log(a); // [3,2,1]

8 "ES6 new method copyWithin (): Copy the members of a specified location to another location

定义:在当前数组内部,将指定位置的成员复制到其他位置,并返回这个数组。

语法:

    array.copyWithin(target, start = 0, end = this.length)

参数:

三个参数都是数值,如果不是,会自动转为数值.

  1. target(必需):从该位置开始替换数据。如果为负值,表示倒数。
  2. start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。
  3. end(可选):到该位置前停止读取数据,默认等于数组长度。使用负数可从数组结尾处规定位置。

浏览器兼容(MDN): chrome 45,Edge 12,Firefox32,Opera 32,Safari 9, IE 不支持

eg1:

        // -2相当于3号位,-1相当于4号位
        [1, 2, 3, 4, 5].copyWithin(0, -2, -1)
        // [4, 2, 3, 4, 5]
        var a=['OB1','Koro1','OB2','Koro2','OB3','Koro3','OB4','Koro4','OB5','Koro5']
        // 2位置开始被替换,3位置开始读取要替换的 5位置前面停止替换
        a.copyWithin(2,3,5)
        // ["OB1","Koro1","Koro2","OB3","OB3","Koro3","OB4","Koro4","OB5","Koro5"] 

9》ES6: fill() 填充数组

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

参数:

第一个元素(必须): 要填充数组的值

第二个元素(可选): 填充的开始位置,默认值为0

第三个元素(可选):填充的结束位置,默认是为this.length

    ['a', 'b', 'c'].fill(7)
    // [7, 7, 7]
    ['a', 'b', 'c'].fill(7, 1, 2)
    // ['a', 7, 'c']

2、不改变原数组的方法(8个)

ES5:slice、join、toLocateString、toStrigin、cancat、indexOf、lastIndexOf

ES7:includes

1》slice():浅拷贝数组的元素

定义: 方法返回一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组对象,且原数组不会被修改。

注意:字符串也有一个slice() 方法是用来提取字符串的,不要弄混了。

语法:

    array.slice(begin, end);

参数:

begin(可选): 索引数值,接受负值,从该索引处开始提取原数组中的元素,默认值为0。

end(可选):索引数值(不包括),接受负值,在该索引处前结束提取原数组元素,默认值为数组末尾(包括最后一个元素)。

    let a= ['hello','world'];
    let b=a.slice(0,1); // ['hello']
    a[0]='改变原数组';
    console.log(a,b); // ['改变原数组','world'] ['hello']
    b[0]='改变拷贝的数组';
     console.log(a,b); // ['改变原数组','world'] ['改变拷贝的数组']

如上:新数组是浅拷贝的,元素是简单数据类型,改变之后不会互相干扰。

如果是复杂数据类型(对象,数组)的话,改变其中一个,另外一个也会改变。

    let a= [{name:'OBKoro1'}];
    let b=a.slice();
    console.log(b,a); // [{"name":"OBKoro1"}]  [{"name":"OBKoro1"}]
    // a[0].name='改变原数组';
    // console.log(b,a); // [{"name":"改变原数组"}] [{"name":"改变原数组"}]
    // b[0].name='改变拷贝数组',b[0].koro='改变拷贝数组';
    //  [{"name":"改变拷贝数组","koro":"改变拷贝数组"}] [{"name":"改变拷贝数组","koro":"改变拷贝数组"}]

  原因在定义上面说过了的:slice()是浅拷贝,对于复杂的数据类型浅拷贝,拷贝的只是指向原数组的指针,所以无论改变原数组,还是浅拷贝的数组,都是改变原数组的数据。

2》join():数组转字符串

定义: 方法返回一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组对象,且原数组不会被修改。

注意:字符串也有一个slice() 方法是用来提取字符串的,不要弄混了。

语法:

    array.join(str)

参数:

str(可选): 指定要使用的分隔符,默认使用逗号作为分隔符。

    let a= ['hello','world'];
    let str=a.join(); // 'hello,world'
    let str2=a.join('+'); // 'hello+world'

使用join方法或者下文说到的toString方法时,当数组中的元素也是数组或者是对象时会出现什么情况?

3》toLocaleString(): 数组转字符串

定义: 返回一个表示数组元素的字符串。该字符串由数组中的每个元素的 toLocaleString() 返回值经调用 join() 方法连接(由逗号隔开)组成。

语法:

 array.toLocaleString()

参数:无。

  let a=[{name:'OBKoro1'},23,'abcd',new Date()];
    let str=a.toLocaleString(); // [object Object],23,abcd,2018/5/28 下午1:52:20 

 

如上述栗子:调用数组的toLocaleString方法,数组中的每个元素都会调用自身的toLocaleString方法,对象调用对象的toLocaleString,Date调用Date的toLocaleString

4》toString():数组转字符串 不推荐

定义: toString() 方法可把数组转换为由逗号链接起来的字符串。

语法:

array.toString()

参数: 无。

该方法的效果和join方法一样,都是用于数组转字符串的,但是与join方法相比没有优势,也不能自定义字符串的分隔符,因此不推荐使用。

值得注意的是:当数组和字符串操作的时候,js 会调用这个方法将数组自动转换成字符串

let b= [ 'toString','演示'].toString(); // toString,演示
let a= ['调用toString','连接在我后面']+'啦啦啦'; // 调用toString,连接在我后面啦啦啦

5》cancat

定义: 方法用于合并两个或多个数组,返回一个新数组。

语法:

 var newArr =oldArray.concat(arrayX,arrayX,......,arrayX)

参数:

arrayX(必须):该参数可以是具体的值,也可以是数组对象。可以是任意多个。

eg1:

  let a = [1, 2, 3];
    let b = [4, 5, 6];
    //连接两个数组
    let newVal=a.concat(b); // [1,2,3,4,5,6]
    // 连接三个数组
    let c = [7, 8, 9]
    let newVal2 = a.concat(b, c); // [1,2,3,4,5,6,7,8,9]
    // 添加元素
    let newVal3 = a.concat('添加元素',b, c,'再加一个'); 
    // [1,2,3,"添加元素",4,5,6,7,8,9,"再加一个"]
   // 合并嵌套数组  会浅拷贝嵌套数组
   let d = [1,2 ];
   let f = [3,[4]];
   let newVal4 = d.concat(f); // [1,2,3,[4]]

ES6扩展运算符...合并数组

因为ES6的语法更简洁易懂,所以现在合并数组我大部分采用...来处理,...运算符可以实现cancat的每个栗子,且更简洁和具有高度自定义数组元素位置的效果。

    let a = [2, 3, 4, 5]
    let b = [ 4,...a, 4, 4]
    console.log(a,b); //  [2, 3, 4, 5] [4,2,3,4,5,4,4]

更多关于扩展符的详细内容移步阮一峰大神的ECMAScript 6 入门

6》indexOf() :查找数组是否存在某个元素,返回下标

定义: 返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

语法:

array.indexOf(searchElement,fromIndex)

参数:

searchElement(必须):被查找的元素

fromIndex(可选):开始查找的位置(不能大于等于数组的长度,返回-1),接受负值,默认值为0。

严格相等的搜索:

数组的indexOf搜索跟字符串的indexOf不一样,数组的indexOf使用严格相等===搜索元素,即数组元素要完全匹配才能搜索成功。

注意:indexOf()不能识别NaN

eg:

 let a=['啦啦',2,4,24,NaN]
 console.log(a.indexOf('啦'));  // -1 
 console.log(a.indexOf('NaN'));  // -1 
 console.log(a.indexOf('啦啦')); // 0

  

使用场景:

  1. 数组去重
  2. 根据获取的数组下标执行操作,改变数组中的值等。
  3. 判断是否存在,执行操作。

7》lastIndexOf(): 查找指定元素在数组中的最后一个位置

定义: 方法返回指定元素,在数组中的最后一个的索引,如果不存在则返回 -1。(从数组后面往前查找)

语法:

 arr.lastIndexOf(searchElement,fromIndex)

参数:

searchElement(必须): 被查找的元素

fromIndex(可选): 逆向查找开始位置,默认值数组的长度-1,即查找整个数组。

关于fromIndex有三个规则:

  1. 正值。如果该值大于或等于数组的长度,则整个数组会被查找。

  2. 负值。将其视为从数组末尾向前的偏移。(比如-2,从数组最后第二个元素开始往前查找)

  3. 负值。其绝对值大于数组长度,则方法返回 -1,即数组不会被查找。

     let a=['OB',4,'Koro1',1,2,'Koro1',3,4,5,'Koro1']; // 数组长度为10
     // let b=a.lastIndexOf('Koro1',4); // 从下标4开始往前找 返回下标2
     // let b=a.lastIndexOf('Koro1',100); //  大于或数组的长度 查找整个数组 返回9
     // let b=a.lastIndexOf('Koro1',-11); // -1 数组不会被查找
     let b=a.lastIndexOf('Koro1',-9); // 从第二个元素4往前查找,没有找到 返回-1
    复制代码

8》ES7 includes() 查找数组是否包含某个元素 返回布尔

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

语法:

array.includes(searchElement,fromIndex=0)

参数:

searchElement(必须):被查找的元素

fromIndex(可选):默认值为0,参数表示搜索的起始位置,接受负值。正值超过数组长度,数组不会被搜索,返回false。负值绝对值超过长数组度,重置从0开始搜索。

includes方法是为了弥补indexOf方法的缺陷而出现的:

  1. indexOf方法不能识别NaN
  2. indexOf方法检查是否包含某个值不够语义化,需要判断是否不等于-1,表达不够直观

eg:

 let a=['OB','Koro1',1,NaN];
 // let b=a.includes(NaN); // true 识别NaN
 // let b=a.includes('Koro1',100); // false 超过数组长度 不搜索
 // let b=a.includes('Koro1',-3);  // true 从倒数第三个元素开始搜索 
 // let b=a.includes('Koro1',-100);  // true 负值绝对值超过数组长度,搜索整个数组

兼容性(MDN): chrome47, Firefox 43,Edge 14,Opera 34, Safari 9,IE 未实现。

3、遍历方法(12个)

js中遍历数组并不会改变原始数组的方法总共有12个:

 

    ES5:
    forEach、every 、some、 filter、map、reduce、reduceRight、
    ES6:
    find、findIndex、keys、values、entries

关于遍历:

  • 关于遍历的效率,可以看一下这篇详解JS遍历
  • 尽量不要在遍历的时候,修改后面要遍历的值
  • 尽量不要在遍历的时候修改数组的长度(删除/添加)

1》forEach

定义: 按升序为数组中含有效值的每一项执行一次回调函数。

语法:

 array.forEach(function(currentValue, index, arr), thisValue)

参数:

function(必须): 数组中每个元素需要调用的函数。

    // 回调函数的参数
    1. currentValue(必须),数组当前元素的值
    2. index(可选), 当前元素的索引值
    3. arr(可选),数组对象本身
复制代码

thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined

关于forEach()你要知道

  • 无法中途退出循环,只能用return退出本次回调,进行下一次回调。
  • 它总是返回 undefined值,即使你return了一个值。

下面类似语法同样适用这些规则

    1. 对于空数组是不会执行回调函数的
    2. 对于已在迭代过程中删除的元素,或者空元素会跳过回调函数
    3. 遍历次数再第一次循环前就会确定,再添加到数组中的元素不会被遍历。
    4. 如果已经存在的值被改变,则传递给 callback 的值是遍历到他们那一刻的值。
复制代码

eg:

 let a = [1, 2, ,3]; // 最后第二个元素是空的,不会遍历(undefined、null会遍历)
    let obj = { name: 'OBKoro1' };
    let result = a.forEach(function (value, index, array) { 
      a[3] = '改变元素';
      a.push('添加到尾端,不会被遍历')
      console.log(value, 'forEach传递的第一个参数'); // 分别打印 1 ,2 ,改变元素
      console.log(this.name); // OBKoro1 打印三次 this绑定在obj对象上
      // break; // break会报错
      return value; // return只能结束本次回调 会执行下次回调
      console.log('不会执行,因为return 会执行下一次循环回调')
    }, obj);
    console.log(result); // 即使return了一个值,也还是返回undefined
    // 回调函数也接受接头函数写法

2》every 检测数组所有元素是否都符合判断条件

定义: 方法用于检测数组所有元素是否都符合函数定义的条件

语法:

  array.every(function(currentValue, index, arr), thisValue)

参数:(这几个方法的参数,语法都类似)

function(必须): 数组中每个元素需要调用的函数。

    // 回调函数的参数
    1. currentValue(必须),数组当前元素的值
    2. index(可选), 当前元素的索引值
    3. arr(可选),数组对象本身

thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined

方法返回值规则:

  1. 如果数组中检测到有一个元素不满足,则整个表达式返回 false,且剩余的元素不会再进行检测。
  2. 如果所有元素都满足条件,则返回 true

eg:

 function isBigEnough(element, index, array) { 
      return element >= 10; // 判断数组中的所有元素是否都大于10
    }
    let result = [12, 5, 8, 130, 44].every(isBigEnough);   // false
    let result = [12, 54, 18, 130, 44].every(isBigEnough); // true
    // 接受箭头函数写法 
    [12, 5, 8, 130, 44].every(x => x >= 10); // false
    [12, 54, 18, 130, 44].every(x => x >= 10); // true

3》some 数组中的是否有满足判断条件的元素

定义:数组中的是否有满足判断条件的元素

语法:

 array.some(function(currentValue, index, arr), thisValue)

参数:(这几个方法的参数,语法都类似)

function(必须): 数组中每个元素需要调用的函数。

    // 回调函数的参数
    1. currentValue(必须),数组当前元素的值
    2. index(可选), 当前元素的索引值
    3. arr(可选),数组对象本身

thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined

方法返回值规则:

  1. 如果有一个元素满足条件,则表达式返回true, 剩余的元素不会再执行检测。

  2. 如果没有满足条件的元素,则返回false

     function isBigEnough(element, index, array) {
       return (element >= 10); //数组中是否有一个元素大于 10
     }
     let result = [2, 5, 8, 1, 4].some(isBigEnough); // false
     let result = [12, 5, 8, 1, 4].some(isBigEnough); // true

4》filter 过滤原始数组,返回新数组

定义: 返回一个新数组, 其包含通过所提供函数实现的测试的所有元素。

语法:

let new_array = arr.filter(function(currentValue, index, arr), thisArg)

参数:(这几个方法的参数,语法都类似)

function(必须): 数组中每个元素需要调用的函数。

    // 回调函数的参数
    1. currentValue(必须),数组当前元素的值
    2. index(可选), 当前元素的索引值
    3. arr(可选),数组对象本身

thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined

eg:

 let a = [32, 33, 16, 40];
    let result = a.filter(function (value, index, array) {
      return value >= 18; // 返回a数组中所有大于18的元素
    });
    console.log(result,a);// [32,33,40] [32,33,16,40]

5》map 对数组中的每个元素进行处理,返回新的数组

定义:创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

语法:

 let new_array = arr.map(function(currentValue, index, arr), thisArg)

参数:(这几个方法的参数,语法都类似)

function(必须): 数组中每个元素需要调用的函数。

    // 回调函数的参数
    1. currentValue(必须),数组当前元素的值
    2. index(可选), 当前元素的索引值
    3. arr(可选),数组对象本身

thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined

eg:

let a = ['1','2','3','4'];
let result = a.map(function (value, index, array) {
  return value + '新数组的新元素'
});
console.log(result, a); 
// ["1新数组的新元素","2新数组的新元素","3新数组的新元素","4新数组的新元素"] ["1","2","3","4"]

6》reduce 为数组提供累加器,合并为一个值

定义:reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,最终合并为一个值。

语法:

 array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

参数:

function(必须): 数组中每个元素需要调用的函数。

    // 回调函数的参数
    1. total(必须),初始值, 或者上一次调用回调返回的值
    2. currentValue(必须),数组当前元素的值
    3. index(可选), 当前元素的索引值
    4. arr(可选),数组对象本身

initialValue(可选): 指定第一次回调 的第一个参数。

回调第一次执行时:

  • 如果 initialValue 在调用 reduce 时被提供,那么第一个 total 将等于 initialValue,此时 currentValue 等于数组中的第一个值;
  • 如果 initialValue 未被提供,那么 total 等于数组中的第一个值,currentValue 等于数组中的第二个值。此时如果数组为空,那么将抛出 TypeError。
  • 如果数组仅有一个元素,并且没有提供 initialValue,或提供了 initialValue 但数组为空,那么回调不会被执行,数组的唯一值将被返回。

eg:

 // 数组求和 
    let sum = [0, 1, 2, 3].reduce(function (a, b) {
      return a + b;
    }, 0);
    // 6
    // 将二维数组转化为一维 将数组元素展开
    let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
      (a, b) => a.concat(b),
      []
    );
     // [0, 1, 2, 3, 4, 5]

  

7》reduceRight 从右至左累加

这个方法除了与reduce执行方向相反外,其他完全与其一致,请参考上述 reduce 方法介绍。

8》ES6:find()& findIndex() 根据条件找到数组成员

find()定义:用于找出第一个符合条件的数组成员,并返回该成员,如果没有符合条件的成员,则返回undefined。

findIndex()定义:返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

这两个方法

语法:

 let new_array = arr.find(function(currentValue, index, arr), thisArg)
 let new_array = arr.findIndex(function(currentValue, index, arr), thisArg)

参数:(这几个方法的参数,语法都类似)

function(必须): 数组中每个元素需要调用的函数。

    // 回调函数的参数
    1. currentValue(必须),数组当前元素的值
    2. index(可选), 当前元素的索引值
    3. arr(可选),数组对象本身

thisValue(可选): 当执行回调函数时this绑定对象的值,默认值为undefined

这两个方法都可以识别NaN,弥补了indexOf的不足.

eg:

  // find
  let a = [1, 4, -5, 10].find((n) => n < 0); // 返回元素-5
  let b = [1, 4, -5, 10,NaN].find((n) => Object.is(NaN, n));  // 返回元素NaN
  // findIndex
  let a = [1, 4, -5, 10].findIndex((n) => n < 0); // 返回索引2
  let b = [1, 4, -5, 10,NaN].findIndex((n) => Object.is(NaN, n));  // 返回索引4

浏览器兼容(MDN):Chrome 45,Firefox 25,Opera 32, Safari 8, Edge yes,

9》ES6 keys()&values()&entries() 遍历键名、遍历键值、遍历键名+键值

定义:三个方法都返回一个新的 Array Iterator 对象,对象根据方法不同包含不同的值。

语法:

 array.keys()
 array.values()
 array.entries()

参数:无。

遍历栗子(摘自ECMAScript 6 入门):

    for (let index of ['a', 'b'].keys()) {
      console.log(index);
    }
    // 0
    // 1
    
    for (let elem of ['a', 'b'].values()) {
      console.log(elem);
    }
    // 'a'
    // 'b'
    
    for (let [index, elem] of ['a', 'b'].entries()) {
      console.log(index, elem);
    }
    // 0 "a"
    // 1 "b"

for..of中如果遍历中途要退出,可以使用break退出循环。

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

    let letter = ['a', 'b', 'c'];
    let entries = letter.entries();
    console.log(entries.next().value); // [0, 'a']
    console.log(entries.next().value); // [1, 'b']
    console.log(entries.next().value); // [2, 'c']
复制代码

entries()浏览器兼容性(MDN):Chrome 38, Firefox 28,Opera 25,Safari 7.1

keys()浏览器兼容性(MDN):Chrome 38, Firefox 28,Opera 25,Safari 8,

注意:目前只有Safari 9支持,,其他浏览器未实现,babel转码器也还未实现



 

 

 

 
 


Guess you like

Origin www.cnblogs.com/yongwunaci/p/11593761.html