js判断数组,对象是否存在某一未知元素

1.对象   

1 var obj = {
2     aa:'1111',
3     bb:'2222',
4     cc: '3333'
5 };
6 var str='aa';
7 if(str in obj){
8     console.log(obj[str]);
9 }

但是对于obj内的原型对象,也会查找到:

1 var obj = {
2     aa:'1111',
3     bb:'2222',
4     cc: '3333'
5 };
6 var str='toString';
7 if(str in obj){
8     console.log(obj[str]);
9 }

所以,使用hasOwnProperty()更准确:

 1 var obj = {
 2     aa: '1111',
 3     bb: '2222',
 4     cc: '3333'
 5 };
 6 var str = 'aa';
 7 if (obj.hasOwnProperty(str)) {
 8     console.log(111);
 9 }else{
10     console.log(222);
11 }

2.数组

如何判断数组内是存在某一元素?主流,或者大部分都会想到循环遍历,其实不循环也可以,通过数组转换查找字符串:

1 var test = ['a', 3455, -1];
2 
3 function isInArray(arr, val) {
4     var testStr = arr.join(',');
5     return testStr.indexOf(val) != -1
6 };
7 alert(isInArray(test, 'a'));

通过While循环:

Array.prototype.contains = function(obj) {
    var len = this.length;
    while (len--) {
        if (this[len] === obj) {
            return true
        }
    }
    return false;
};

for循环:

Array.prototype.contains = function(obj) {
    var len = this.length;
    for (var i = 0; i < len; i++) {
        if (this[i] === obj) {
            return true
        }
    }
    return false;
}
原文地址:https://www.cnblogs.com/peng14/p/4848672.html