1

here is my html code

<p id="b1" onclick="clickFunction(this)" >+</p>
<p id="b2" onclick="clickFunction(this)">+</p>
<p id="b3" onclick="clickFunction(this)">+</p>
<p id="b4" onclick="clickFunction(this)">+</p>
<p id="b5" onclick="clickFunction(this)">+</p>
<p id="b6" onclick="clickFunction(this)">+</p>
<p id="b7" onclick="clickFunction(this)">+</p>
<p id="b8" onclick="clickFunction(this)">+</p>
<p id="b9" onclick="clickFunction(this)">+</p>

here is my javascript code

var status = [2, 2, 2, 2, 2, 2, 2, 2, 2];
var gameStatus = {
    b1: 2,
    b2: 2,
    b3: 2,
    b4: 2,
    b5: 2,
    b6: 2,
    b7: 2,
    b8: 2,
    b9: 2
}

function clickFunction(element) {
    var ids = element.id
    document.write(gameStatus.ids) //but it returns undefined
};

Now I want to take the id and use that id to call the object in the gameStatus gameStatus.id is giving me undefined.

I tried all the methods like converting it to number or string but nothing works.

Converting it to number give me Nan and converting it to sting and then using it gives me undefined. Please help me

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Kartik Puri
  • 467
  • 3
  • 13
  • Have a look at how [property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) work – Patrick Evans Jul 15 '17 at 10:12
  • you can use gameStatus[element.id] to access the value of the corresponding property in the gameStatus object. – Kaloyan Jul 15 '17 at 10:38

1 Answers1

0

Try with another method of object.value call obj[varible]

In your method obj.ids ids refer to keyname of the object not the variable of ids

var status=[2,2,2,2,2,2,2,2,2];
var gameStatus={b1:2,b2:2,b3:2,b4:2,b5:2,b6:2,b7:2,b8:2,b9:2}
function clickFunction(element){
var ids = element.id
document.write(gameStatus[ids])//but it returns undefined
}
<p id="b1" onclick="clickFunction(this)">+</p>
<p id="b2" onclick="clickFunction(this)">+</p>
<p id="b3" onclick="clickFunction(this)">+</p>
<p id="b4" onclick="clickFunction(this)">+</p>
<p id="b5" onclick="clickFunction(this)">+</p>
<p id="b6" onclick="clickFunction(this)">+</p>
<p id="b7" onclick="clickFunction(this)">+</p>
<p id="b8" onclick="clickFunction(this)">+</p>
<p id="b9" onclick="clickFunction(this)">+</p>
prasanth
  • 22,145
  • 4
  • 29
  • 53