前端面试题:如何给一个数组添加一个自定义方法

1、了解prototype

     JavaScript中的prototype属性到底是啥意思?

2、给官方对象(类)Array增加方法,也是使用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>
发布了219 篇原创文章 · 获赞 347 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/jiang7701037/article/details/99973153