Object.prototype.hasPubProperty = function(property) {
//=>验证传递的属性名合法性(一般只能是数字或字符串等基本值)
if(!["string","number","boolean"].includes(typeof property)) return false;
//=>开始校验是否为公有属性(方法中的this就是要校验的对象)
let n = property in this;
let m = this.hasOwnProperty(property);
return n && !m;
}
console.log(Array.prototype.hasPubProperty('push')); //=>false
console.log([].hasPubProperty('push')); //=>true
2、数组去重
Array.prototype.myUnique = function() {
//=> 使用ES6 Set进行数组去重
let set = new Set(this);
//=> [...set]类数组转数组,也可以是用Array.from(set)转数组
return [...set];
}
let ary = [12,3,44,55,55,66,66];
console.log(ary.myUnique()); //=>[12, 3, 44, 55, 66]
3、数组去重后排序
Array.prototype.myUniqueSort = function() {
let set = new Set(this);
//=> 链式调用(保证当前方法执行完返回的结果依然是Array类的实例)
return [...set].sort((a, b) => a - b );
}
let ary = [12, 3, 44, 55, 55, 66, 66, 0];
console.log(ary.myUniqueSort()); //=>[0, 3, 12, 44, 55, 66]