一、所有的数组实例都继承于 Array.prototype。
二、所有的数组方法都定义在 Array.prototype 身上,和其他的构造函数一样,你可以通过扩展 Array 的 prototype 属性上的方法来给所有数组实例增加方法。
Array.prototype 本身也是个数组。
Array.isArray(Array.prototype); // true
三、Array.prototype 属性表示 Array 构造函数的原型,并允许您向所有Array对象添加新的属性和方法。
-
给 Array 对象添加新的方法——返回数组中项的下标
Array.prototype.indexOf = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) return i;
}
return -1;
};
-
给Array对象添加新的方法——删除数组中某一项
Array.prototype.remove = function (val) {
var index = this.indexOf(val)
let arr = []
for (var i = 0; i < this.length; i++) {
if (i != index) arr.push(this[i])
}
return arr
}
const arr = ['apple','pear','banana','watermelon','pineapple']
console.log(arr.remove('banana')) // ['apple', 'pear', 'watermelon', 'pineapple']
同理,String.prototype用于为某字符串对象新增方法,比如:
-
给String对象添加新的方法——将某字符串重复n次
String.prototype.times = function(n) {
return (new Array(n+1)).join(this);
};
var str = 'a'
console.log(str.times(3)) // aaa