js判断数组中是否存在某个字符串存在就删除,不存在就插入数组

js原生代码判断某个字符串再数组中是否存在,存在就删除掉该字符串,不存在就将该字符串插入到数组中。

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
window.onload = function(){
var a=["六月初","六月初博客站","六月初个人博客站"];
var local = a.indexOf("六月初博客站");
if(local == -1){
a.push("六月初博客站")
}else{
a.splice(local,1)
}
console.log(a);

var b=["六月初","六月初博客站","六月初个人博客站"];
var newadd = b.indexOf("六月");
if(newadd == -1){
b.push("六月")
}else{
b.splice(newadd,1)
}
console.log(b);

}
</script>
</body>
</html>

效果如图:


代码基础解析:

通过indexOf来判断你需要处理的字符串再数组中是否存在,存在就会返回所在数组的下标,不存在就会返回-1

之后,根据返回的值来进行数组的截取和插入操作,即push和splice


六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!