Cooper Reck Cooper Reck - 4 days ago 4
Javascript Question

How do I use an if statement using object property, then replace the object property?

I want to create a series of if statements based on the object "pest"'s property of "state" and then replace it with a new state. How can I do this?

<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>




<script>

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"
}


}

Answer

Yes that is possible. I would also use === just in case as that makes sure that the type is the same...i.e. you are comparing a string to a string. You would want to also do pest.state, instead of pest ["state"].

Just so the answer is actual within the selected answer:

When creating an object in JS it should be done in the following way:

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

To access attributes in the object do the following:

pest.state; pest.type;
Comments