查找数组值

Find array value

本文关键字:数组 查找      更新时间:2023-10-26

我的数组:

var PrivateChatList = [];

按键和值(仅举一例):

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

我想在函数上找到"player4"键。我怎么能找到?

function getObjectKeyFromValue(object, value)
{
    for(var k in object)
    {
        if(object[k] == value)
        {
            return k;
        }
    }
    return '';
}
var key = getObjectKeyFromValue(PrivateChatList, 'player4')
alert(key); // 'supporter4'