简体   繁体   中英

Objects: Value always undefined

I am working on some keybinding functionality and came across something that is quite confusing to me.

I am doing some regex validation against the user defined keybinding pattern and would then like to assign the pattern as key and value to definedKeys:

 const definedPattern = ['a', 'b'] let definedKeys = {} const bindKeys = () => { const charKey = (String(definedPattern[0]) + String(definedPattern[1])).match(/^[a-zA-Z]{2}$/) if (charKey) { definedKeys[charKey.input[0]] = definedKeys[charKey.input[1]] } console.log(definedKeys) } bindKeys()

Isn't it because you don't put anything in definedKeys but instead you put it in definedCharKeys?

  • Use definedKeys instead of definedCharKeys as it is not declared neither initailized

  • Assigning value directly to key instead of refrencing value from definedKeys because value is not still set and it will be always undefined .

  definedKeys = {};
  const encodeKey = (pKey) => {
      charKey = (String(pKey[0]) + String(pKey[1])).match(/^[a-zA-Z]{2}$/);
      if (charKey) {
          // charKey.input = 'ab'
          definedKeys[charKey.input[0]] = charKey.input[1];
      }
  }

  encodeKey('ab');
  console.log(definedKeys);

As per the code. You are not assigning anything in "definedKeys". You are assigning a value in "definedCharKeys" that's why you are getting undefined for the "definedKeys".

Please post full code where are you calling the function so that developers can provide you solution.

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