在JS中,判断一个数组中是否包含某个值,一般用indexOf(),今天我们用contains,跟写java一样判断数组包含某个值,但是js原生是没有数组的contains,所以我们要先自己封装一下,给Array增加contains()方法了
封装contains
Array.prototype.contains = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) {
return true;
}
}
return false;
};
使用contains
var arrFileNames = ["pdf","jpg","jpeg","bmp","gif","mov","flash","mkv"];//定义一个数组
if(arrFileNames.contains("jpg")){
//如果arrFileNames数组里包含"jpg" 返回true
console.log(true);
} else{
console.log(false);
}
详细javascript代码
<!DOCTYPE html>
<html>
<head>
<title>像java一样使用js contains 实践笔记</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
$(function() {// 初始化内容
testContains();
});
//封装contains
Array.prototype.contains = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) {
return true;
}
}
return false;
};
//使用contains
function testContains(){
var arrFileNames = ["pdf","jpg","jpeg","bmp","gif","mov","flash","mkv"];//定义一个数组
if(arrFileNames.contains("jpg")){
//如果arrFileNames数组里包含"jpg" 返回true
console.log(true);
alert(arrFileNames.contains("jpg"));//true
} else{
console.log(false);
arrFileNames.contains("jpg");//false
}
}
</script>
</html>