[英]Objects: Value always undefined
我正在研究一些键绑定功能,遇到了一些让我很困惑的东西。
我正在对用户定义的键绑定模式进行一些正则表达式验证,然后想将该模式作为键和值分配给 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()
不是因为你没有在definedKeys 中放任何东西,而是将它放在definedCharKeys 中吗?
使用definedKeys
而不是definedCharKeys
,因为它没有声明也没有初始化
将 value 直接分配给 key 而不是从definedKeys
引用 value 因为 value 尚未设置并且它将始终为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);
根据代码。 您没有在“definedKeys”中分配任何内容。 您正在“definedCharKeys”中分配一个值,这就是为什么您没有为“definedKeys”定义。
请发布完整代码,您在哪里调用 function,以便开发人员为您提供解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.