搜索javascript枚举

时间:2015-05-26 15:53:17

标签: javascript

我有以下javascript枚举:

// Rooms
var rooms = {
 1: 'First Room',
 2: 'Second Room',
 3: 'Third Room',
};

我可以轻松地获得如下房间描述:

// Get Room Description
var roomOne = 1;
var roomdesc = rooms[roomOne];

如果我的房间描述'First Room'并且我想获得房间号码怎么样?

我试过了:

// Get room number
var roomIndex = rooms.indexOf('First Room');
var roomNum = rooms[roomIndex];

但indexOf未定义。如何按房间描述获取房间号?

由于

PS:忘了提。我不能改变房间的对象。它已经在其他领域使用!另外,我想在不使用原型或jquery的情况下这样做。感谢。

3 个答案:

答案 0 :(得分:1)

试试这个:

var rooms = {
    1: 'First Room',
    2: 'Second Room',
    3: 'Third Room',
};

function test(val){
 for (var key in rooms) {
   if(rooms.hasOwnProperty(key))
    if (rooms[key] == val) {
        alert("Key:"+key);
    }
 }
}
test('First Room');//Pass the value you want to search for

答案 1 :(得分:0)

我建议您将Array用于此目的:



var rooms = ['First Room','Second Room','Third Room'];
// Get Room Description
var roomOne = 0;
var roomdesc = rooms[roomOne];
// Get room number
var roomIndex = rooms.indexOf('First Room');
var roomNum = rooms[roomIndex];

console.log( roomNum )




不是数组首先被编入索引。

答案 2 :(得分:-2)

试试这个:

var test = {
    1: 'First Room',
    2: 'Second Room',
    3: 'Third Room',
};
function getKeyByValue (obj, value) {
    for( var prop in obj ) {
        if( obj.hasOwnProperty( prop ) ) {
             if( obj[ prop ] === value )
                 return prop;
        }
    }
}
console.log(getKeyByValue( test, "Second Room" ));  // logs 2