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内的原型对象,也会查找到:this
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()更准确:spa
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.数组prototype
如何判断数组内是存在某一元素?主流,或者大部分都会想到循环遍历,其实不循环也能够,经过数组转换查找字符串:code
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循环:blog
Array.prototype.contains = function(obj) { var len = this.length; for (var i = 0; i < len; i++) { if (this[i] === obj) { return true } } return false; }