A front end face questions: How to add a custom method to an array

1, understand prototype

     prototype property in JavaScript in the end What do you mean?

 

2, to the official target (class) increased Array method is the use of prototype

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style type="text/css">
       
    </style>
</head>
<body>
    <input type="button" value="测试" onclick="testf()"  />
</body>
</html>

<script type="text/javascript">

//这是个面试题:如何给官方的类增加方法。
Array.prototype.max = function () {
    let m = this[0];//this是数组对象,调用max函数的数组对象
    for(let i=1;i<this.length;i++){
        if(this[i]>m){
            m = this[i];
        }
    }
    return m;
}

let arr = new Array(12,222,13,50,18);

let m = arr.max();
console.log(m);

</script>

 

Published 219 original articles · won praise 347 · views 340 000 +

Guess you like

Origin blog.csdn.net/jiang7701037/article/details/99973153