本文实例讲述了JS实现数组删除指定元素功能。分享给大家供大家参考,具体如下:<!DOCTY
本文实例讲述了JS实现数组删除指定元素功能。分享给大家供大家参考,具体如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>www.jb51.net JS数组删除指定元素</title>
</head>
<body>
<script>
var array = ["111", "222", "333", "444", "555", "666"];
var indexList = [0, 5, 6];
var indexList1 = [5];
Array.prototype.del = function(indexList) {
function isValidate(number) {
if(isNaN(number) && number > this.length) {
return false;
}
}
if(indexList instanceof Array) {
indexList.sort(function(x, y) {
if(x > y) {
return 1;
} else {
return -1;
}
});
var lastIndex = indexList[indexList.length - 1];
isValidate(lastIndex);
for(var i = 0; i < indexList.length; i++) {
var n = i;
if(n > 0) {
indexList[i] = indexList[i] - n;
}
this.splice(indexList[i], 1);
n++;
}
} else {
isValidate(indexList);
this.splice(indexList, 1);
}
}
console.log("before delete: " + array);
array.del(indexList1);
console.log("after delete: " + array);
</script>
</body>
</html>
运行结果:
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。
JS 数组 删除 指定元素