如果对象在数组中,最好的方法是什么?

这是我知道的最好的方式:

函数include(arr,obj){对于(变量i=0;i<arr.length;i++){如果(arr[i]==obj)返回true;}}console.log(包括([1,2,3,4],3));//真的console.log(包括([1,2,3,4],6));//未定义


当前回答

这里详细介绍了一种检查对象是否为javascript中的数组的健壮方法:

这里是xa.js框架中的两个函数,我将它们附加到utils={}“容器”。这些应该可以帮助您正确检测阵列。

var utils = {};

/**
 * utils.isArray
 *
 * Best guess if object is an array.
 */
utils.isArray = function(obj) {
     // do an instanceof check first
     if (obj instanceof Array) {
         return true;
     }
     // then check for obvious falses
     if (typeof obj !== 'object') {
         return false;
     }
     if (utils.type(obj) === 'array') {
         return true;
     }
     return false;
 };

/**
 * utils.type
 *
 * Attempt to ascertain actual object type.
 */
utils.type = function(obj) {
    if (obj === null || typeof obj === 'undefined') {
        return String (obj);
    }
    return Object.prototype.toString.call(obj)
        .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};

如果你想检查一个对象是否在一个数组中,我也会包括以下代码:

/**
 * Adding hasOwnProperty method if needed.
 */
if (typeof Object.prototype.hasOwnProperty !== 'function') {
    Object.prototype.hasOwnProperty = function (prop) {
        var type = utils.type(this);
        type = type.charAt(0).toUpperCase() + type.substr(1);
        return this[prop] !== undefined
            && this[prop] !== window[type].prototype[prop];
    };
}

最后,这个in_array函数:

function in_array (needle, haystack, strict) {
    var key;

    if (strict) {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

其他回答

[].有(obj)

假设实现了.indexOf()

Object.defineProperty( Array.prototype,'has',
{
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        }
        return false;                       
    },
    // writable:false,
    // enumerable:false
})

!!! 不要将Array.protocol.hhas=function()设置为{…,因为您将在每个数组中添加一个可枚举元素,js将被破坏。

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

第二个参数(标志)的使用强制按值而不是参照进行比较

比较原始对象

[o1].has(o2,true) // true if every level value is same

这里详细介绍了一种检查对象是否为javascript中的数组的健壮方法:

这里是xa.js框架中的两个函数,我将它们附加到utils={}“容器”。这些应该可以帮助您正确检测阵列。

var utils = {};

/**
 * utils.isArray
 *
 * Best guess if object is an array.
 */
utils.isArray = function(obj) {
     // do an instanceof check first
     if (obj instanceof Array) {
         return true;
     }
     // then check for obvious falses
     if (typeof obj !== 'object') {
         return false;
     }
     if (utils.type(obj) === 'array') {
         return true;
     }
     return false;
 };

/**
 * utils.type
 *
 * Attempt to ascertain actual object type.
 */
utils.type = function(obj) {
    if (obj === null || typeof obj === 'undefined') {
        return String (obj);
    }
    return Object.prototype.toString.call(obj)
        .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};

如果你想检查一个对象是否在一个数组中,我也会包括以下代码:

/**
 * Adding hasOwnProperty method if needed.
 */
if (typeof Object.prototype.hasOwnProperty !== 'function') {
    Object.prototype.hasOwnProperty = function (prop) {
        var type = utils.type(this);
        type = type.charAt(0).toUpperCase() + type.substr(1);
        return this[prop] !== undefined
            && this[prop] !== window[type].prototype[prop];
    };
}

最后,这个in_array函数:

function in_array (needle, haystack, strict) {
    var key;

    if (strict) {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

如果使用jQuery:

$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);

有关详细信息:http://api.jquery.com/jQuery.inArray/

首先,在JavaScript中为还没有indexOf的浏览器实现它。然后,您可以使用indexOf而不必担心浏览器支持。下面是他的indexOf实现的一个稍微优化的版本:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
    };
}

它被更改为存储长度,因此不需要每次迭代都查找它。但差别并不大。不太通用的函数可能更快:

var include = Array.prototype.indexOf ?
    function(arr, obj) { return arr.indexOf(obj) !== -1; } :
    function(arr, obj) {
        for(var i = -1, j = arr.length; ++i < j;)
            if(arr[i] === obj) return true;
        return false;
    };

我更喜欢使用标准函数,并在真正需要时保留这种微优化。但是,如果你热衷于微优化,我调整了评论中与公鸡酸相关的基准,以在数组中进行基准搜索。虽然它们很粗糙,但全面的调查将测试不同类型、不同长度的阵列,并找到不同位置的对象。

这取决于你的目的。如果您为Web编程,请避免indexOf,它不受Internet Explorer 6支持(其中许多仍在使用!),或者进行条件使用:

if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);
else result = customSlowerSearch(yourArray, target);

indexOf可能是用本机代码编写的,所以它比用JavaScript做的任何事情都要快(如果数组合适的话,除了二进制搜索/二分法)。注意:这是一个品味问题,但我会做一个错误的返回;在例程结束时,返回一个真正的布尔值。。。