Insert int for listing in javascript

How do you efficiently use int to enumerate in javascript?

Say I have this listing

enuTable = // Table enum
{
    enuUnknown: 0,
    enuPerson: 1,
    enuItem: 2,
    enuSalary: 3,
    enuTax: 4,
    enuZip: 5,
    enuAddress: 6,
    enuLocation: 7,
    enuTasks: 8,

};

In the code part, I get the return value from an AJAX call, which is a number corresponding to one of the above tables.

, , ( ) int ? , , . , , , . , , .

+4
4

var keys = Object.keys(enuTable).sort(function(a, b){
    return enuTable[a] - enuTable[b];
}); //sorting is required since the order of keys is not guaranteed.

var getEnum = function(ordinal) {
    return keys[ordinal];
}

UPD: ,

var keys = Object.keys(enuTable).reduce(function(acc, key) {
    return acc[enuTable[key]] = key, acc;
}, {});
+8

:

 function toTableName(i) {
     for(var p in enuTable) {
         if(enuTable.hasOwnProperty(p) && enuTable[p] === i) {
              return p;
         }
     }
     throw new Error('that\ no table...');
}
+2

, JavaScript , # .

, , AJAX switch, Number JavaScript, - :

switch(ajaxNumber) {
   case enuTable.enuPerson: 
      break;
}

(, enuPerson), ( jsFiddle):

// We're going to implement a basic enumeration prototype to generalize
// what you're looking for so you may re-use this code anywhere!
function Enum(valueMap) {
    // We store the enumeration object
    this._valueMap = valueMap;
    this._valueToLabelMap = {};
    var that = this;

    // This will create an inverse map: values to labels
    Object.keys(valueMap).forEach(function (label) {
        that._valueToLabelMap[valueMap[label]] = label;
    });
}

Enum.prototype = {
    // Getting the whole label is as simple as accessing
    // the inverse map where values are the object properties!
    getLabel: function (value) {
        if (this._valueToLabelMap.hasOwnProperty(value)) {
            return this._valueToLabelMap[value];
        } else {
            throw Error("Enum instance has no defined '" + value + "' value");
        }
    }
};

var enuTable = new Enum({
    enuUnknown: 0,
    enuPerson: 1,
    enuItem: 2,
    enuSalary: 3,
    enuTax: 4,
    enuZip: 5,
    enuAddress: 6,
    enuLocation: 7,
    enuTasks: 8,
});

// Now, if we provide a number, the fancy Enum prototype will handle it
// so you're going to get the whole enumeration value label!
var taxLabel = enuTable.getLabel(45);
+1

, , , ( (). @YuryTarabanko, ?

The solution that I will come up with is one thing. You can access it in the same way as Yuri’s solution (keys [ajaxResponseNumber]). I tested it with jsPerf and it is faster in Firefox, but in this case it is not relevant.

var keys = {}; for (var x in enuTable) { if (enuTable.hasOwnProperty(x)) { keys[enuTable[x]] = x; } }

0
source

All Articles