自己的菜鸟写法:
var arr=["12",323,"ab","dss",313]; var obj={"age":18, "name":"sun", "addr":"shanghai" };//其实对象,直接obj["mail"]==undefined就可以判断是否存在,主要判断数组 console.log(indexOf("sun",obj)); console.log(indexOf("abc",arr)); function indexOf(str,obj){ var num=0; for(var a in obj){ if(str===obj[a]){ num=1; break; }else{ num=-1; } } return num; }
写在原型链的方式:
var arr = new Array("jayc","yaoming","kobe"); var name = "yaoming"; if(!Array.indexOf){ Array.protoType.indexOf = function(Object){ for(var i = 0;i<this.length;i++){ if(this[i] == Object){ return i; } } return -1; } var searchId = arr.indexOf(name); alert(searchId); }