如何使用object属性使用if语句,然后替换object属性?

时间:2016-12-01 02:50:31

标签: javascript

我想根据对象""" state"的属性创建一系列if语句。然后用新状态替换它。我怎么能这样做?

<body>

<img style="vertical-align:middle" id="pet" src="https://i.imgsafe.org/f726448be6.png">
<table>
<tr>
  <th><button id="feed" onclick="buttonFeed"> Feed </button></th>
  <th><button id="10pm" onclick="buttonLate"> 10pm </button></th>
  <th><button id="play" onclick="buttonPlay"> Play </button></th>
  <th><button id="pet" onclick="buttonPet"> Pet </button></th>
  <th><button id="cuddle" onclick="buttonCuddle"> Cuddle </button></th>
</tr>
</table>

var pest = {
    type:"dog",
    state:"Happy"}

function buttonFeed() {
  if (pest.state === "Happy" || "Relaxed") {
    pest.state = "Sleepy"
    document.getElementById("pet").src="https://i.imgsafe.org/f726267ded.png"
  } else if (pest.state === "Hungry" || "Michevous") {
    pest.state = "Happy"
    document.getElementById("pet").src="https://i.imgsafe.org/f726448be6.png"
  } else if (pest.state === "Sleepy") {
    pest.state = "Relaxed"
    document.getElementById("pet").src="https://i.imgsafe.org/f72630373c.png"
  }
}

1 个答案:

答案 0 :(得分:-1)

是的,这是可能的。我也会使用===以防万一,因为这确保了类型是相同的...即。您正在将字符串与字符串进行比较。你也想做pest.state,而不是害虫[&#34; state&#34;]。

所以答案在所选答案中是实际的:

在JS中创建对象时,应按以下方式完成:

var pest = {state: "Happy", type: "dog"};

要访问对象中的属性,请执行以下操作:

pest.state; pest.type;

在if语句中检查多个值时,请使用以下命令:

if (pest.state === "Happy" || pest.state === "Relaxed")

在引用Javascript的html中进行的函数调用也需要括号:

Onclick="buttonFeed()"