控制台日志给我“未定义”。我找不到使用“ addBook”函数在myBox对象内添加对象属性的方法。也许我只是说错了,但我认为这应该是正确的方法。

  function addBook (box, name, writer) {
  box["# of Books"]++;
  box["book" + box["# of Books"]] = {title: name, author: writer};
  }

  var myBox = {
  height: 10,
  width:50,
  volume:400
  };


  addBook(myBox, "Javascript Ninja", "Ninja");
  console.log(myBox.book1.title);

最佳答案

问题是您尝试增加未定义的值,因此得到NaN

只需初始化您的计数器:

 function addBook (box, name, writer) {
  box["# of Books"]++;
  box["book" + box["# of Books"]] = {title: name, author: writer};
  }

  var myBox = {
  height: 10,
  width:50,
  volume:400
  };
  myBox["# of Books"]=0; // <-- there


  addBook(myBox, "Javascript Ninja", "Ninja");
  console.log(myBox.book1.title);


遇到此类问题时,您应该首先自己调试它,逐步查看值。阅读Debugging JavaScript

09-27 19:01