Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
增加或减少对象中的值-javascript_Javascript - Fatal编程技术网

增加或减少对象中的值-javascript

增加或减少对象中的值-javascript,javascript,Javascript,我想在点击金额+1的“预订”按钮后增加对象中的值,怎么做 var hotel = { name : "King", rooms: 40, booked: 25, checkAvailability: function() { return this.rooms - this.booked; } }; function decA(){ hotel.booked[ this + 1 ]; } var elName = document.getElementById(

我想在点击金额+1的“预订”按钮后增加对象中的值,怎么做

var hotel = {
  name : "King",
  rooms: 40,
  booked: 25,
  checkAvailability: function() {
    return this.rooms - this.booked;
  }
};

function decA(){
 hotel.booked[ this + 1 ];
}

var elName = document.getElementById("hotelname");
elName.textContent = hotel.name + hotel.rooms;

var elRooms = document.getElementById("demo");
elRooms.textContent = hotel.checkAvailability();

我认为这不起作用的原因是变量的范围仅在变量
hotel
内,因为在变量
hotel
内定义了。您可以在变量
hotel
之外定义它(例如在文档顶部),然后在变量
hotel
内使用它。这应该是可行的。

您可以定义一个函数来获取和设置内部范围,如:

var hotel = {
  name : "King",
  rooms: 40,
  booked: 25,
  checkAvailability: function() {
    return this.rooms - this.booked;
  },
  bookARoom: function () {
    return this.booked++;
  },
  getBookedRoom: function () {
    return this.booked;
  }
};

您可以调用hotel.getBookedRoom()和hotel.bookARoom()来获取和设置内部作用域

hotel.booked[this+1]
并不会做您认为它会做的事情–您可以修改hotel:
hotel.booked+=1
–或者创建一个新的hotel:
{……hotel,booked:hotel.booked+1}