简体   繁体   中英

Javascript Array To Lookup Key Value Pairs

I would like to be able to create an object that I could use in conjunction with the following code that could convert keycodes into the appropriate key name.

$(document).keydown(function(event) {
  var keycode = (event.keyCode ? event.keyCode : event.which);
  if (keycode === 37) {
    $('#content').html('You pressed the "<strong>Left Arrow</strong>" key');
  } else if (keycode == 39) {
    $('#content').html('You pressed the "<strong>Right Arrow</strong>"     key');
  } else if (keycode == 38) {
    $('#content').html('You pressed the "<strong>Up Arrow</strong>" key');
  } else if (keycode == 40) {
    $('#content').html('You pressed the "<strong>Down Arrow</strong>" key');
  } else {
    $('#content').html('You pressed a key that triggers a(n) <input class="keycode" value="' + event.which + '" /> code');
  }
});

http://codepen.io/Realto619/pen/OpErLL

What would a logical way to do something like that entail? KeyValuePair, JSON, Data Dictionary or something else altogether?

I would use a map called keyNames that converts between your keyCode s and their name strings (eg 'Left Arrow' ). Also note that you can replace your use of the ternary operator ( event.keyCode ? event.keyCode event.which ) with the shorter logical or version ( event.keyCode || event.which ).

 var keyNames = { 37: 'Left Arrow', 38: 'Up Arrow', 39: 'Right Arrow', 40: 'Down Arrow' } $(document).keydown(function (event) { var keyCode = event.keyCode || event.which $('#content').html(keyCode in keyNames ? 'You pressed the "<strong>' + keyNames[keyCode] + '</strong>" key' : 'You pressed a key that triggers a(n) <input class="keycode" value="' + keyCode + '" /> code' ) }) 
 html { font-family: sans-serif; font-size: 13px } .keycode { font-family: monospace; font-weight: bold; font-size: 20px; width: 60px; text-align: center; } 
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> Press a key. Any key.<br /><br /> <div id="content"></div> 

JSON, Key-value pair, Data dictionaries - all of these are nothing but Javascript objects.

You can declare an object with keys as keycodes and values as something you want to use. In the example below, they are strings.

$(document).keydown(function(event) {
  var keyMap = { 37: 'Left', 38: 'Up', 39: 'Right', 40: 'Down' };
  var keycode = (event.keyCode ? event.keyCode : event.which);

  if (keyMap[keycode]) {
    $('#content').html('You pressed the "<strong>' + keyMap[keycode] + ' Arrow</strong>" key');
  } else {
    $('#content').html('You pressed a key that triggers a(n) <input class="keycode" value="' + event.which + '" /> code');
  }
});

You can also write functions as values and call them if you want to perform an action.

$(document).keydown(function(event) {
  var keyMap = {
    37: function () {
      console.log('handle left');
    },
    38: function () {
      console.log('handle up');
    },
    39: function () {
      console.log('handle right');
    },
    40: function () {
      console.log('handle down');
    },
  };

  var keycode = (event.keyCode ? event.keyCode : event.which);

  if (keyMap[keycode]) {
    keyMap[keycode]();
  } else {
    console.log('This key is not handled');
  }
});

Here is one way to accomplish your goal:

var keys = {
   "slash": 191, 
   "up": 38, 
   "down": 40, 
   "left": 37, 
   "right": 39, 
   "enter": 13, 
   "space": 32, 
   "ctrl": 17, 
   "alt": 18, 
   "tab": 9, 
   "esc": 27
};

Then you could use it like this:

if (keyCode === keys.enter) {
   ....
}

I would take the approach of an array of objects with keyCode and keyName values, and use array filter/reduce methods to create the string I want.

 const keyLookup = [ { keyCode: 37, keyName: 'Left Arrow' }, { keyCode: 39, keyName: 'Right Arrow' } ]; $(document).keydown(function(event) { const keyString = keyLookup .filter(key => key.keyCode === (event.keyCode ? event.keyCode : event.which)) .reduce((keysPressed, key) => keysPressed += key.keyName, ''); $('#content').html(`You pressed the ${keyString} key.`); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="content"></div> 

Try below Code: This code Uses JSON to map key pressed, with its value as key name .

 var keyPair = { "8": "backspace", "9": "tab", "13": "enter", "16": "shift", "17": "ctrl", "18": "alt", "19": "pause/break", "20": "caps lock", "27": "esc", "32": "space", "33": "page up", "34": "page down", "35": "end", "36": "home", "37": "left", "38": "up", "39": "right", "40": "down", "45": "insert", "46": "delete", "48": "0", "49": "1", "50": "2", "51": "3", "52": "4", "53": "5", "54": "6", "55": "7", "56": "8", "57": "9", "65": "a", "66": "b", "67": "c", "68": "d", "69": "e", "70": "f", "71": "g", "72": "h", "73": "i", "74": "j", "75": "k", "76": "l", "77": "m", "78": "n", "79": "o", "80": "p", "81": "q", "82": "r", "83": "s", "84": "t", "85": "u", "86": "v", "87": "w", "88": "x", "89": "y", "90": "z", "91": "left command", "93": "right command", "96": "numpad 0", "97": "numpad 1", "98": "numpad 2", "99": "numpad 3", "100": "numpad 4", "101": "numpad 5", "102": "numpad 6", "103": "numpad 7", "104": "numpad 8", "105": "numpad 9", "106": "numpad *", "107": "numpad +", "109": "numpad -", "110": "numpad .", "111": "numpad /", "112": "f1", "113": "f2", "114": "f3", "115": "f4", "116": "f5", "117": "f6", "118": "f7", "119": "f8", "120": "f9", "121": "f10", "122": "f11", "123": "f12", "144": "num lock", "145": "scroll lock", "182": "my computer", "183": "my calculator", "186": ";", "187": "=", "188": ",", "189": "-", "190": ".", "191": "/", "192": "`", "219": "[", "220": "\\\\", "221": "]", "222": "'" } $(document).keydown(function(event) { var keycode = (event.keyCode ? event.keyCode : event.which); if (keyPair.hasOwnProperty(keycode)) { $('div').text("You Pressed - " + keyPair[keycode]) } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Press any key here : <br/> <div></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM