使用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>
|