用原型函数(prototype)可以定义一些很方便的自定义函数,实现各种自定义功能。本次主要是实现了Array的去重、获取最大值和最小值。
实现代码如下:
<script type="text/javascript">
Array.prototype.unique = function() {
var a = {};
var len = this.length;
for (var i = 0; i < len; i++) {
if (typeof a[this[i]] == "undefined") {
a[this[i]] = 1;
}
}
this.length = 0;
for (var i in a) {
this[this.length] = i;
}
return this;
}
Array.prototype.max = function() {
return Math.max.apply({}, this);
}
Array.prototype.min = function() {
return Math.min.apply({}, this);
}
var arr = [7,3,9,7,6,2,4,2,8];
console.log(arr.unique());
console.log(arr.max());
console.log(arr.min());
</script>
这个例子写太好了
本文介绍如何使用JavaScript的prototype特性为Array类型添加自定义方法,包括去除重复元素、获取最大值和最小值等功能。通过这些自定义方法,可以简化数组操作,提高开发效率。
159

被折叠的 条评论
为什么被折叠?



