如何让用户访问 Javascript 中的对象?

How do I make the user acces an object in Javascript?

我是新手,但我已经完成了一些关于 freecodecamp 的课程。假设我制作了一个关于汽车的对象。我希望网页用户能够编写“Ford Mustang”,然后弹出存储在对象 fordMustang 中的所有信息供用户阅读。

我尝试了一些不同的策略,但无法让它发挥作用。 这是我写的代码,

        <label for="navn">
            <input type="text" id="field" class="field" name="navn">
            <input type="submit" value="send" id="send" class="send">
        </label> <p id="par"> </p>

let fordMustang = {
producer: "Ford",
type: "Mustang",
engine: "v8",
horsePower: 300 }
const inputField = document.querySelector(".field");
const press = document.querySelector("#send");
const para = document.querySelector("#par");

function objScan() {
    const word = String(inputField.value);
    if (word == "Ford Mustang") {
        para.textContent = fordMustang;
    }
    else {
        para.textContent = "Not recognized"
    }
}
press.addEventListener("click", objScan);

你快到了。您只需将 const para 标识符从 id 更改为 class。并使用 innerHTML

添加一些有意义的换行符或您希望在标签内显示的任何样式

let fordMustang = {
  producer: "Ford",
  type: "Mustang",
  engine: "v8",
  horsePower: 300
}
const inputField = document.querySelector(".field");
const para = document.querySelector(".par");

function objScan() {
  const word = String(inputField.value);
  if (word == "Ford Mustang") {
    let result = ""
    Object.entries(fordMustang).map(entries => result += entries[0] + ": " + entries[1] + "<br>")
    para.innerHTML = result
  } else {
    para.textContent = "Not recognized"
  }
}
<label for="navn">
            <input type="text" id="field" class="field" name="navn" value="Ford Mustang">
            <input type="submit" value="send" id="send" class="send" onclick="objScan()">
        </label>
<p id="par" class="par"> </p>

您可以使用 JSON.stringify() 来实现。 您需要将 para.textContent = fordMustang; 替换为 JSON.stringify(fordMustang);

let fordMustang = {
producer: "Ford",
type: "Mustang",
engine: "v8",
horsePower: 300 }
const inputField = document.querySelector(".field");
const press = document.querySelector("#send");
const para = document.querySelector("#par");

function objScan() {
    const word = String(inputField.value);
    if (word == "Ford Mustang") {
        para.textContent = JSON.stringify(fordMustang);
    }
    else {
        para.textContent = "Not recognized"
    }
}
press.addEventListener("click", objScan);
<label for="navn">
            <input type="text" id="field" value="Ford Mustang" class="field" name="navn">
            <input type="submit" value="send" id="send" class="send">
        </label> <p id="par"> </p>