查找数组值

时间:2015-02-12 17:09:05

标签: javascript arrays

我的阵列:

var PrivateChatList = [];

按下键和值(仅举例):

PrivateChatList['supporter1'] = 'player1';
PrivateChatList['supporter2'] = 'player2';
PrivateChatList['supporter3'] = 'player3';
PrivateChatList['supporter4'] = 'player4';
PrivateChatList['supporter5'] = 'player5';
PrivateChatList['supporter6'] = 'player6';
PrivateChatList['supporter7'] = 'player7';

我想在功能上找到“player4”键。我怎么能找到?

1 个答案:

答案 0 :(得分:1)

function getObjectKeyFromValue(object, value)
{
    for(var k in object)
    {
        if(object[k] == value)
        {
            return k;
        }
    }
    return '';
}

var key = getObjectKeyFromValue(PrivateChatList, 'player4')
alert(key); // 'supporter4'