如何给数组添加一个自定义方法

论坛 期权论坛 脚本     
匿名技术用户   2020-12-30 18:25   11   0

使用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>给数组添加自定义方法</title>
</head>
<body>
    <input type="button" value="测试" οnclick="test()"/>
</body>
</html>
<script>
// 给数组添加一个自定义方法,判断数组中的最大值
Array.prototype.max = function test(){
    let m = this[0];  //this是数组对象,调用max函数的数组对象
    for(let i=0;i<this.length;i++){
        if(this[i]>m){
            m = this[i];
        }
    }
    return m;
}
let arr = new Array(12,13,11,10,9,5,4);
let m = arr.max();
console.log(m);
</script>

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP