0
点赞
收藏
分享

微信扫一扫

【JavaScript】自定义函数之检查数组中是否存在某个值

豆丁趣 2022-04-21 阅读 46
javascript

代码

/**
 * 检查数组中是否存在某个值
 *
 * @param {String}       needle   待搜索的值,区分大小写
 * @param {Array|Object} haystack 待搜索的数组
 * @param {Boolean}      strict   没有设置 strict 则使用宽松的比较
 *
 * @return {Boolean}
 * @throws `needle` Arguments Error
 * @throws `haystack` Arguments Is Not Array
 */
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) )
// 结果:true

let needle2 = 'catalogue2';
let haystack2 = {
    'catalogue': 'catalogue2',
    'menu': 'menu',
    '0': 'data'
};
console.log( in_array(needle2, haystack2) )
// 结果:false

let needle3 = 0;
console.log( in_array(needle3, haystack2) )
// 结果:true
console.log( in_array(needle3, haystack2, true) )
// 结果:false

console.log( in_array(needle2, 'test') )
// 抛出异常:Uncaught `haystack` Arguments Is Not Array

举报

相关推荐

0 条评论