简体   繁体   English

jQuery $ .inArray似乎不适用于关联数组

[英]jQuery $.inArray doesn't seem to work with associative arrays

I have made this fiddle: http://jsfiddle.net/benhowdle89/CANX8/1/ 我做了这个小提琴: http//jsfiddle.net/benhowdle89/CANX8/1/

Which creates an assoc array and then runs a test for a value that is in the array. 这将创建一个assoc数组,然后对数组中的值运行测试。 The wrong results are reached! 达到了错误的结果!

Outline of code: 代码大纲:

$(document).ready(function(){
    var newArray = [];
    newArray['first'] = 1;
    newArray['second'] = 1;

    $('button').click(function(){
        if($.inArray(1, newArray) != -1){
            $('#dump').css('border', '1px solid red');
        } else {
            $('#dump').css('border', '1px solid blue');
        }
    });
});
var newArray = [];
newArray['first'] = 1;
newArray['second'] = 1;

This will not add any elements to the array. 这不会向数组添加任何元素。 You can see newArray.length will be zero. 你可以看到newArray.length将为零。

Instead it adds properties first and second to newArray . 相反,它将firstsecond属性添加到newArray

You can access it using 您可以使用它访问它

newArray.first
newArray.second

So $.inArray will not work 所以$.inArray不起作用

The indices of a JavaScript array are unsigned 32 bit integers and therefore you can't use strings, see http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/ JavaScript数组的索引是无符号32位整数,因此您不能使用字符串,请参阅http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/

However, you can use something like this: 但是,您可以使用以下内容:

function findPropertyWithValue(obj, val) {
    for (var i in obj) {
        if (obj.hasOwnProperty(i) && obj[i] === val) {
            return i;
        }
    }
    return null;
}

var arr = [];
arr['A string'] = '123';
arr['Another string'] = '456';
alert(findPropertyWithValue(arr, "123")); // 'A string'

inArray works for integer-access based arrays. inArray适用于基于整数访问的数组。

var len;

    if ( array ) {
        if ( indexOf ) {
            return indexOf.call( array, elem, i );
        }

        len = array.length;
        i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

        for ( ; i < len; i++ ) {
            // Skip accessing in sparse arrays
            if ( i in array && array[ i ] === elem ) {
                return i;
            }
        }
    }

    return -1;

That's how jQuery does it. 这就是jQuery如何做到的。 It does not iterate using a for(var i in arr)... (of course with the hasOwnProperty validation, it would be ;)) but only by index access according to length. 它不使用for(var i in arr)迭代...(当然使用hasOwnProperty验证,它将是;))但只能通过索引访问长度。

As the documentation says: http://api.jquery.com/jQuery.inArray/ it is similar to the native indexOf method. 正如文档所述: http//api.jquery.com/jQuery.inArray/它类似于原生indexOf方法。 Seens the native indexOf does it this way, jQuery follows by having a similar behavior. 看看本机indexOf是这样做的,jQuery遵循类似的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM