目前国企等一些单位仍然使用的xp等历史系统,就不得不面对ie8的对各种脚本兼容性问题了。下面是在数组中判断某元素是否存在和删除数组中指定元素做一个简单的笔记,方便后续查找,也希望能帮助有需要的js新手。
1、判断数组中是否存在某个元素
<script>
// 给数组添加属性regStr; fromCharCode() 函数的功能是将Unicode编码转换为字母
// 关于此函数的更多介绍: https://www.runoob.com/jsref/jsref-fromcharcode.html
Array.prototype.regStr = String.fromCharCode(2);
// 给数组添加函数isExist
Array.prototype.isExist= function (e) {
var r = new RegExp(this.regStr + e + this.regStr);
return (r.test(this.regStr + this.join(this.regStr) + this.regStr));
};
// 测试方法
function testMain(){
// 声明数组并添加元素
var userIdArr=[];
userIdArr.push(1);
userIdArr.push(2);
userIdArr.push(3);
// 输出结果为 true
console.info(userIdArr.isExist(2));
}
</script>
2、删除数组中指定的元素
<script>
// 给数组添加indexOf函数,功能是返回元素所在的下标;正常情况下Array自带此函数,但ie8须显式重写
Array.prototype.indexOf = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) return i;
}
return -1;
};
// 给数组添加remove 函数,即删除指定元素。
Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
// 测试
function testMain(){
// 声明数组并添加元素
var userIdArr=[];
userIdArr.push(1);
userIdArr.push(2);
userIdArr.push(3);
// 调用函数删除指定元素
userIdArr.remove(2);
// 将数组转换为字符串输出
console.info(userIdArr.toString());
}
</script>