代码
function in_array(needle, haystack, strict)
{
strict = strict?strict:false;
if ( typeof strict !== 'boolean' ){
throw "`strict` Arguments Is Not Boolean";
}
if( typeof needle!=='string' && typeof needle!=='number' ){
throw "`needle` Arguments Error";
}
if( !haystack || typeof haystack!=='object' ){
throw "`haystack` Arguments Is Not Array";
}
var isIndexArray = false;
if ( typeof haystack ==='object' ){
if( haystack.constructor===Array ){
isIndexArray = true;
}
}
let _in = false;
if( isIndexArray === true ){
_in = haystack.indexOf(needle)>=0;
}else{
for(var key in haystack){
_in = strict===true?key===needle:key==needle;
if( _in ){break;}
}
}
return _in;
}
测试示例
let needle = 'catalogue';
let haystack = [
'catalogue',
'menu'
];
console.log( in_array(needle, haystack) )
let needle2 = 'catalogue2';
let haystack2 = {
'catalogue': 'catalogue2',
'menu': 'menu',
'0': 'data'
};
console.log( in_array(needle2, haystack2) )
let needle3 = 0;
console.log( in_array(needle3, haystack2) )
console.log( in_array(needle3, haystack2, true) )
console.log( in_array(needle2, 'test') )