JS& jQuery:如果索引是字符串,则inArray()和indexOf()无法正常工作? [英] JS & jQuery: inArray() and indexOf() are not working properly if indexes are strings?

查看:84
本文介绍了JS& jQuery:如果索引是字符串,则inArray()和indexOf()无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

var arr = [];
arr['A string'] = '123';
arr['Another string'] = '456';

我正试图找到索引"123"或"456".

两者:

var string = $.inArray('123', arr)

var string = arr.indexOf('123')

给我-1.当索引是字符串时,能否使其正常工作?

解决方案

问题是您将JavaScript数组用作关联数组,指出了这一点,但我认为很多JavaScript开发人员会坚持使用整数来说明问题.*

I have an array like this:

var arr = [];
arr['A string'] = '123';
arr['Another string'] = '456';

and Im trying to find an index of '123' or '456'.

Both:

var string = $.inArray('123', arr)

and

var string = arr.indexOf('123')

are giving me -1. Is it possible to get it working when indexes are strings?

解决方案

The problem is that you are using a JavaScript array as an associative array, something that it is not. The indices of a JavaScript array are unsigned 32 bit integers and therefore you can't use *strings**. You would either use an array like so

// I'm guessing that you meant to give numerical and not string values
var arr = [123, 456];

or use an object

var obj = { 
    'A string' : 123,
    'Another string' : 456
};

Note that using an object, 'A string' and 'Another string' are properties of object obj and can't be indexed like the values in an array. You can check that an object has a property a number of ways, one of which would be using hasOwnProperty

if (obj.hasOwnProperty('A string')) {
    // if obj has property 'A string' as a direct property
}

another would be using the in keyword

if ('A string' in obj) {
    // if obj has a property 'A string' as a property (could be an inherited property too)
}

**unless the string is the string representation of a 32 bit unsigned integer as Tim points out, but I think it's fair to say that a lot of JavaScript developers would say stick to using integers for clarity.*

这篇关于JS& jQuery:如果索引是字符串,则inArray()和indexOf()无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆