我试图根据密钥返回一组值。我想要返回的值取决于用户输入的密钥。但是,当我迭代我的for循环时,我收到一条错误说:TypeError: Cannot read property 'length' of undefined
。我做错了什么?
var obj = {
14: ['abc', 'def', 'gh', 'i', 'k'],
90: ['asdf','xxc' , 'd'],
92: ['def', 'dr' , 'vvd', 'off']
}
exports.function(key) = {
var temp = {};
for(var i = 0; i < obj.key.length; i++){
temp[i] = obj.key[i];
}
return temp;
};
答案 0 :(得分:1)
正如我在评论中所说,object.key
正在寻找一个名为key
的属性。如果要访问由用户输入定义的属性,则必须使用[]
语法。在您的情况下,[key]
。
试试这个:
exports.function(key) = {
return obj[key];
};
或者,以snippit形式,
var obj = {
14: ['abc', 'def', 'gh', 'i', 'k'],
90: ['asdf','xxc' , 'd'],
92: ['def', 'dr' , 'vvd', 'off']
};
function getKey(key){
return obj[key];
}
console.log(getKey(14))
console.log(getKey(92))
答案 1 :(得分:0)
如果我理解正确:
var obj = {
14: ['abc', 'def', 'gh', 'i', 'k'],
90: ['asdf','xxc' , 'd'],
92: ['def', 'dr' , 'vvd', 'off']
}
function test(key) = {
return obj[key];
};
test(14) //returns ['abc', 'def', 'gh', 'i', 'k']
test(92) //returns ['def', 'dr' , 'vvd', 'off']