不明白为什么这显示为未定义



我开始构建一个简单的文本冒险游戏,但根本无法解决这个问题。我在文本框中键入"检查表"。Inspect被剥离,只留下表,然后将其传递给Inspect功能。当我尝试将innerHTML更改为input.description时,我会得到未定义。然而,当我使用table.description时,它运行良好。

const text = document.querySelector('#text');
const userForm = document.querySelector('#user-form');
let userInput = document.querySelector('#user-input');
const table = {
description: 'Plates and silverware are on the table',
items: ['plates', 'silverware'],
itemDescrips: ['rotting food sits on the plates.', 'just silverware']
};  
let inspect = function(input) {
//Returns undefined
text.innerHTML = input.description;
//Oddly, this works fine
//text.innerHTML = table.description
};
userInput.addEventListener('keydown', (e) => {

if (e.keyCode == 13) {
let command = userInput.value.split(' ');
if (command.includes('inspect')) {
//I've checked the type of this argument and it is a string.
inspect(command[1]);
}
userForm.reset();**strong text**
e.preventDefault();
} 
});

你们让我思考,并帮助我意识到我可以在inspect函数中使用条件逻辑来实现这一点。

let inspect = function(input) {
if (input == 'table') {
text.innerHTML = table.description;
}
};

您正在向inspect函数传递一个简单的文本,而该文本没有名为description的属性。这就是为什么你会得到一个未定义的回报。

仅将参数输入分配到文本中。innerHTML效果良好。

let inspect = function(input) {
text.innerHTML = input;
};

最新更新