在做一个网站,用vue cli搭建的框架。
通过扩展数组的原型来实现删除指定元素。
首先查找索要删除的元素在数组中的位置。
Array.prototype.indexOf = function(val)
{
for (var i = 0; i < this.length; i++)
{
if (this[i] == val) return i;
}
return -1;
};
接下来删除指定位置的元素
Array.prototype.remove = function(val)
{
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
完成了上面2段代码后,在使用数组对象的时候就可以用remove()这个方法来删除元素了。比如像下面这样:
var temp = ['aaa','bbb','ccc','ddd'];
console.log(temp);
temp.remove('ccc');
console.log(temp);
运行结果
![](https://img.haomeiwen.com/i19063106/72229d7afed3ac92.png)
OK,现在只要把上面两段JS代码放到main.js的created事件方法里,整个工程的数组就都可以使用了。
![](https://img.haomeiwen.com/i19063106/ea9ff47c7adad14c.png)
网友评论