Home > Web Front-end > JS Tutorial > body text

Application of call and apply in javascript

php中世界最好的语言
Release: 2018-03-14 13:30:03
Original
1396 people have browsed it

This time I will bring you the application of call and apply in javascript, what are the precautions for the application of call and apply in javascript, the following is a practical case, let’s take a look .

Find the maximum and minimum values ​​of the array

Define an array:

var ary = [23, 34, 24, 12, 35, 36, 14, 25];
Copy after login

Sort and then take the value method

First, perform the array Sorting (small -> large), the first and last are the minimum and maximum values ​​we want.

var ary = [23, 34, 24, 12, 35, 36, 14, 25];
ary.sort(function (a, b) {
    return a - b;
});var min = ary[0];var max = ary[ary.length - 1];
console.log(min, max);1234567
Copy after login

Assumption method

Assume that the first value in the current array is the maximum value, and then compare this value with the following items one by one. If one of the latter values ​​is greater than the assumed value Hit, indicating that the assumption is wrong, we replace the assumed value...

var max = ary[0], min = ary[0];for (var i = 1; i < ary.length; i++) {
    var cur = ary[i];
    cur > max ? max = cur : null;
    cur < min ? min = cur : null;
}
console.log(min, max);1234567
Copy after login

The max/min method in Math is implemented (through apply)

Use Math.min

directly
var min = Math.min(ary); 
console.log(min); // NaN 
console.log(Math.min(23, 34, 24, 12, 35, 36, 14, 25));
Copy after login

When using Math.min directly, you need to pass the pile of numbers to be compared one by one, so that you can get the final demerit. It is not possible to put an ary array in at once.

Try: Use eval

var max = eval(“Math.max(” + ary.toString() + “)”); 
console.log(max); 
var min = eval(“Math.min(” + ary.toString() + “)”); 
console.log(min); 
“Math.max(” + ary.toString() + “)” –> “Math.max(23,34,24,12,35,36,14,25)”
Copy after login

Don’t worry about anything else first, first change the last code we want to execute into String, and then put it in the array The value of each item is spliced ​​into this string separately.

eval: Convert a string into a JavaScript expression for execution
For example: eval(“12+23+34+45”) // 114

Call through apply max/min in Math

var max = Math.max.apply(null, ary); 
var min = Math.min.apply(null, ary); 
console.log(min, max);
Copy after login

In non-strict mode, when the first parameter to apply is null, this in max/min will be pointed to window, and then the ary parameters will be passed one by one. Give max/min.

Find the average

Now simulate a scenario and conduct a certain competition. After the judges score, they are required to remove the highest score and the lowest score, and the average of the remaining scores is for the final score.

Maybe many students will think of writing a method to receive all the scores, and then use the built-in attribute arguments of the function to sort the arguments by calling the sort method, and then..., but it should be noted that arguments are not A real array object is just a collection of pseudo-arrays, so directly calling the sort method with arguments will report an error:

arguments.sort(); // Uncaught TypeError: arguments.sort is not a function
Copy after login


So at this time, can you convert the arguments into a real array first? , and then proceed with the operation. According to this idea, we implement a business method to achieve the requirements of the question:

function avgFn() {
    // 1、将类数组转换为数组:把arguments克隆一份一模一样的数组出来
    var ary = [];    for (var i = 0; i < arguments.length; i++) {
        ary[ary.length] = arguments[i];
    }    // 2、给数组排序,去掉开头和结尾,剩下的求平均数
    ary.sort(function (a, b) {
        return a - b;
    });
    ary.shift();
    ary.pop();    return (eval(ary.join(&#39;+&#39;)) / ary.length).toFixed(2);
}var res = avgFn(9.8, 9.7, 10, 9.9, 9.0, 9.8, 3.0);
console.log(res);1234567891011121314151617
Copy after login

We found that there is a step in the avgFn method we implemented to clone the arguments and generate them. is an array. If you are familiar with the slice method of arrays, you can know that when no parameters are passed to the slice method, the current array is cloned, which can be simulated as:

function mySlice () {
    // this->当前要操作的这个数组ary
    var ary = [];    for (var i = 0; i < this.length; i++) {
        ary[ary.length] = this[i];
    }    return ary;
};var ary = [12, 23, 34];var newAry = mySlice(ary);
console.log(newAry);1234567891011
Copy after login

So in the avgFn method, the arguments are converted into arrays The operation can be borrowed from the slice method in Array through the call method.

function avgFn() { // 1、将类数组转换为数组:把arguments克隆一份一模一样的数组出来 // var ary = Array.prototype.slice.call(arguments); var ary = [].slice.call(arguments);
// 2、给数组排序,去掉开头和结尾,剩下的求平均数....123
}
Copy after login

Our current approach is to convert arguments into an array first, and then operate the converted array. Can we just use arguments directly instead of converting them into an array first? Of course it is possible, it can be achieved by borrowing the array method through call.

function avgFn() {
    Array.prototype.sort.call(arguments , function (a, b) {
        return a - b;
    });
    [].shift.call(arguments);
    [].pop.call(arguments);    return (eval([].join.call(arguments, &#39;+&#39;)) / arguments.length).toFixed(2);
}var res = avgFn(9.8, 9.7, 10, 9.9, 9.0, 9.8, 3.0);
console.log(res);123456789101112
Copy after login

Convert class array to array

As mentioned before, use the slice method of the array to convert the array-like object into an array, then obtain it through getElementsByTagName and other methods Can an array-like object also use the slice method to convert it into an array object?

var oLis = document.getElementsByTagName('div');
var ary = Array.prototype.slice.call(oLis);
console.log(ary);
In standard It can indeed be used in this way under the browser, but it will be a tragedy under IE6~8, and an error will be reported:

SCRIPT5014: Array.prototype.slice: 'this' is not a JavaScript object (error report)
Then in Under IE6~8, you can only add them to the array one by one through a loop:

for (var i = 0; i < oLis.length; i++) { 
ary[ary.length] = oLis[i]; 
}
Copy after login

Note: There is no compatibility problem with the method of borrowing arrays for arguments.

Based on the difference between IE6~8 and standard browsers, extract the tool class for converting array-like objects into arrays:

function listToArray(likeAry) {
    var ary = [];    try {
        ary = Array.prototype.slice.call(likeAry);
    } catch (e) {        for (var i = 0; i < likeAry.length; i++) {
            ary[ary.length] = likeAry[i];
        }
    }    return ary;
}1234567891011
Copy after login

This tool method uses browser exceptions Information capture, so let’s introduce it here.

console.log(num);
When we output an undefined variable, an error will be reported: Uncaught ReferenceError: num is not defined. In JavaScript, this line will report an error, and the following code will not Executed again.

But if try..catch is used to capture exception information, it will not affect the execution of the following code. If an error occurs during the execution of the code in try, the try in catch will be executed by default {

console.log(num); 
} catch (e) { // 形参必须要写,我们一般起名为e 
console.log(e.message); // –> num is not defined 可以收集当前代码报错的原因 
} 
console.log(‘ok’);
Copy after login

So the usage format of try...catch is (very similar to Java):

try { 
// 
} catch (e) { 
// 如果代码报错执行catch中的代码 
} finally { 
// 一般不用:不管try中的代码是否报错,都要执行finally中的代码 
}
Copy after login

At this time, I want to capture the information, but I don’t want the following diamante to be executed. So what should be done?

try {    console.log(num);
} catch (e) {    // console.log(e.message); // --> 可以得到错误信息,把其进行统计    // 手动抛出一条错误信息,终止代码执行    throw new Error(&#39;当前网络繁忙,请稍后再试&#39;);    // new ReferenceError --> 引用错误    // new TypeError --> 类型错误    // new RangeError --> 范围错误
}console.log(&#39;ok&#39;);
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

What are the differences between call, apply and bind in javascript

Detailed explanation of call in javascript

The above is the detailed content of Application of call and apply in javascript. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!