[ES5 New Feature 4] Array New Method

There are many new array methods in ES5. Using these methods can greatly reduce the time cost of development and make the code more readable. Let us take a look below, what are the new methods?

Native JavaScriptScipt case collection
JavaScript + DOM basic
JavaScript basic to advanced
Canvas game development

Compare and think about these methods with the previous traditional way of processing logic, and try to intercept and implement these related methods through prototypes.

1.1 Judgment array

  • The first way to determine the instantiated object

    obj instanceof Array
    
  • The second way to determine the constructor

    obj.constructor === Array
    
  • The third way to determine the type of object

    Object.prototype.toString.call(obj)
    
  • The fourth static method of array (new in ES5)

    Array.isArray(obj)
    

Code example :

// instanceof 
console.log(obj instanceof Array); // false
console.log(arr instanceof Array); // true
// 当构造函数是Object的时候也会返回true
console.log(arr instanceof Object); // true

// constructor
console.log(obj.constructor === Array); // fasle
console.log(arr.constructor === Array); // true
console.log(arr.constructor === Object); // false
	
// 判断对象的类型
console.log(Object.prototype.toString.call(obj) === "[object Array]"); // false
console.log(Object.prototype.toString.call(arr) === "[object Array]"); // true
// ES5拓展的静态方法
console.log(Array.isArray(obj)); // false
console.log(Array.isArray(arr)); // true

1.2 Get the index of the array member

indexOf(item,?startIndex) returns the position where a specified element first appears in the array

lastIndexOf(item,?startIndex) returns the last position of a specified element in the array, searching forward from the back of the string

  1. When using both methods, if the element to be retrieved does not appear, -1 will be returned.
  2. For both methods, if the second parameter is omitted, the search starts from the first or last index. Browsers support these two methods, but IE8 and earlier IE versions do not support this method.
  3. There will be no type conversion during the search process, but a true congruent search.

Code demo :

// 创建一个数组
var arr = ["apple","orange","banana","pear","orange","kiwi fruit","orange","peach"];

// 利用ES5方法获取指定成员第一次和最后一次出现的位置
// indexOf() 返回一个指定的元素在数组中第一次出现的位置
// console.log(arr.indexOf("orange"));//1  不指定起始索引,默认从0开始
// console.log(arr.indexOf("orange",2));//4 从第2个索引开始向后查找
// lastIndexOf()  返回一个指定的元素在数组中最后出现的位置
// console.log(arr.lastIndexOf("orange"));//6  不指定索引,默认从最后一个开始向前查找
// console.log(arr.lastIndexOf("orange",5));//4 从第5个索引开始向前查找


// indexOf() 返回一个指定的元素在数组中第一次出现的位置
console.log(arr.indexOf("orange"));//1  不指定起始索引,默认从0开始
console.log(arr.indexOf("orange",2));//4 从第2个索引开始向后查找
// lastIndexOf()  返回一个指定的元素在数组中最后出现的位置
console.log(arr.lastIndexOf("orange"));//6  不指定索引,默认从最后一个开始向前查找
console.log(arr.lastIndexOf("orange",5));//4 从第5个索引开始向前查找

1.3 Array traversal

forEach(function(currentValue, index, arr)) method is used to call each element of the array and pass the element to the callback function

Parameters : Required, it is a callback function, the function that needs to be called for each element in the array, the function parameters are as follows:

  • currentValue is required. elements in the current array
  • index is optional. the index of the current element
  • arr Optional. The array object to which the current element belongs

Note : 1. forEach() will not execute callback function for empty array

  1. forEach is used to replace the for loop, but the for loop is not removed, but the for loop is placed inside the forEach method of the array iterator
  2. The inner scope of the callback function is window
  3. The return value in the callback function has no impact on the execution result of the forEach method. The return value of the forEach method is always undefined.

Code Example :
Requirement: Traverse Array

// 创建一个数组
var arr = ["apple","orange","banana","pear","kiwi fruit","peach"];

// 1. 使用普通的for进行遍历
// console.group("使用普通的for进行遍历");
// for(var i = 0; i < arr.length; i++){
//     console.log("索引",i,"对应的数组元素为:",arr[i],"原数组为:",arr);
// }
// console.log("全局中打印i的值:",i);//全局中打印i的值: 6  全局中保存了i的值,i是全局变量
// console.groupEnd();

// // 2. 使用for...in循环进行遍历
// console.group("使用for...in循环进行遍历");
// for(var idx in arr){
//     console.log("索引",idx,"对应的数组元素为:",arr[idx],"原数组为:",arr);
//     // 注意打印结果:这里的index是字符串,利用的是 对象["属性"] 的方式获取数组中元素的值
// }
// console.log("全局中打印idx:",idx);//全局中打印idx: 5  全局中保存了idx的值,idx是全局变量
// console.groupEnd();

// // 3. 利用ES5新增方法进行遍历
// console.group("利用ES5新增方法进行遍历");
// arr.forEach(function(value,index,array){
//     console.log("索引",index,"对应的数组元素为:",value,"原数组为:",array);
// });
// //console.log("全局中打印index:",index);//报错 Error: index is not defined  说明index在forEach中是局部变量,避免全局变量的污染
// console.groupEnd();

1.4 Mapping Arrays

The map(function(currentValue,index,arr)) method processes each element of the array through the specified function and returns the processed array

Parameters : Same as forEach

Return value : A new array. Each item in the array is a new member composed of the results of each function execution.
Requirement: Capitalize the first letter of each member in the array and return

// 创建一个数组
var arr = ["apple","orange","banana","pear","kiwi fruit","peach"];

console.log("原数组:",arr);//原数组: (6) ["apple", "orange", "banana", "pear", "kiwi fruit", "peach"]

// var mapArr = arr.map(function(value,index,array){
//     // 获取每一个成员字符串的第一个字符,并将其转为大写,拼接到原字符串中
//     var newVal = value.charAt(0).toUpperCase().concat(value.substring(1));
//     // 将转换后的新元素返回
//     return newVal;
// });

// console.log("进行处理后的数组为:",mapArr);//进行处理后的数组为: (6) ["Apple", "Orange", "Banana", "Pear", "Kiwi fruit", "Peach"]

var mapArr = arr.map(function(value,index,array){
    // 获取每一个成员字符串的第一个字符,并将其转为大写,拼接到原字符串中
    var newVal = value.charAt(0).toUpperCase().concat(value.substring(1));
    // 将转换后的新元素返回
    return newVal;
});

console.log("进行处理后的数组为:",mapArr);

1.5 Filling the array

The fill(value, start, end) method fills the array with a fixed value

Parameters : value Required. The filled value start is optional. Start filling position end Optional. Stop filling position (default is array.length)

Note: This method will change the original array

// 创建一个数组
// var arr = ["apple","orange","banana","pear","peach"];
// console.log("填充前原数组arr:",arr);
// // 使用固定值填充数组
// arr.fill("kiwi fruit");
// console.log("填充后原数组arr:",arr);//(5) ["kiwi fruit", "kiwi fruit", "kiwi fruit", "kiwi fruit", "kiwi fruit"] 默认填充每一个数组

// console.log("========= 分割线 =========");

// // 创建一个数组
// var arr2 = ["apple","orange","banana","pear","peach"];
// console.log("填充前原数组arr2:",arr2);//填充前原数组arr2: (5) ["apple", "orange", "banana", "pear", "peach"]
// // 指定索引之间的填充  左闭右开
// arr2.fill("kiwi fruit",2,4);
// console.log("填充后原数组arr2:",arr2);//填充后原数组arr2: (5) ["apple", "orange", "kiwi fruit", "kiwi fruit", "peach"]

// 创建一个数组
var arr3 = ["apple","orange","banana","pear","peach"];
console.log(arr3);
console.log("========= fill填充 =========")
// 指定索引之间的填充  左闭右开
arr3.fill("kiwi fruit",2,4);
console.log(arr3);

1.6 Affirmations

  • some(function(currentValue,index,arr) method is used to detect whether the elements in the array meet the specified conditions (provided by the function)

    The some() method executes each element of the array in turn:

    • If one element satisfies the condition, the expression returns true, and the remaining elements will not perform detection
    • Returns false if there is no element that satisfies the condition.
  • every(function(currentValue,index,arr) method is used to detect whether all elements of the array meet the specified conditions (provided by the function)

    The every() method detects all elements in an array using the specified function:

    • If it is detected that one element in the array is not satisfied, the entire expression returns false and the remaining elements will not be tested again.
    • Returns true if all elements satisfy the condition

Some method code example :
Requirement: Detect whether there is a number greater than 50 in the array

// 定义一个数字
// var arr = [10,20,30,50,60,70,80,90];

// // 使用函数定义条件
// function checkNum(num){
//     return num >= 50;
// }

// // 使用some()检测
// var flag = arr.some(checkNum);
// console.log(flag);//true

Every method code example :
Requirement: Check whether the numbers in the array are greater than 50

// 定义一个数字
var arr = [10,20,30,50,60,70,80,90];
// 使用函数定义条件
function checkNum(num){
    return num >= 50;
}
// 使用every()检测
var flag = arr.every(checkNum);
console.log(flag);//false

Requirement: Determine whether the names in the array are all three characters

var pArr = ["张翠花","王二狗","李大壮","张狗蛋"];
var flag = pArr.every(function(value,index,arr){
    
    
    return value.length === 3;
})
console.log(flag);//true

// 兼容IE8及以下版本...
if(!Array.prototype.every){
    
    
    Array.prototype.every = function(){
    
    
        //...
    }
}

1.7 Filtering

filter() detects numeric elements and returns an array of all elements that meet the conditions

Return value Returns an array containing all elements that meet the conditions. If there are no elements that meet the condition, an empty array is returned.

Requirement: Detect all numbers greater than 50 in the array and return

// 定义一个数字
var arr = [10,20,30,50,60,70,80,90];
// 使用函数定义条件
function checkNum(num){
    return num >= 50;
}
// 使用filter()检测
var resultArr = arr.filter(checkNum);
console.log(resultArr);//(5) [50, 60, 70, 80, 90]

1.8 Accumulator

  • The reduce() method receives a function as an accumulator. Each value in the array (from left to right) starts to be reduced and finally calculated to a value.

  • The function of reduceRight() method is the same as that of reduce(). The difference is that reduceRight() accumulates the array items in the array from the end of the array forward.

    Parameters : It is a function that receives one parameter. There are four parameters in the function: the current accumulated result, the current member value, the current index value, and the original array.

    Return value : The accumulated result will be passed as the first parameter in the next traversal.

Note: 1. reduce is accumulated from front to back, reduceRight is accumulated from back to front. These two methods will process all members one by one and return the results.

// 创建一个数组
var arr = [10,20,30,40,50,60];

// 创建累加器需要的函数
// function sum(total,num){
//     return total + num;
//     // return total * num;
// }
// // reduce()累加器完成累加
// var result = arr.reduce(sum);

// 匿名方式
var result = arr.reduce(function(total,value,index,array){
    return total + value;
})
console.log(result);//累加结果:210

// reduceRight()  累乘等效果
function multiple(total,num){
    return total * num;
}
var result2 = arr.reduceRight(multiple);
console.log(result2);//累乘结果:720000000

1.9 bind method

call(), apply() and bind() methods: These three methods are used to execute functions and change the this point of the function.

  • call method: receives multiple parameters. The first parameter is the this point to be changed. Starting from the second parameter, all parameters are passed.
  • apply method: receives two parameters. The first parameter is the this point to be changed. The second parameter is an array. Each item in the array is the passed parameter.
  • The bind method is similar to the call method. They both execute the function and change the scope of the function.
    • The bind method receives multiple parameters: the first parameter is the this pointer to be changed, and starting from the second parameter are all passed parameters.
    • The difference between the bind method and call: after call changes the pointer of this, the function will be executed again; after bind changes this, the function will not be executed and a function bound to the new this will be returned.
function sum(a,b){
    return a+b;
}

function reduce(a,b){
    return a-b;
}

var test = sum.apply(reduce,[10,20]);
console.log(test);//30

var test1 = sum.call(reduce,10,20);
console.log(test1);//30

var test2 = sum.bind(reduce,10,20);
console.log(test2);//ƒ sum(a,b){return a+b;}
console.log(test2());//30

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/132575918