0

I have vast experience with C, but I'm fairly new using JavaScript. I've been searching for an explanation, but it seems like I'm not phrasing my question right. I need to tell a function which GLOBAL variable it should change. Here's the code:

<!DOCTYPE html>
<html>
 <head>
  <script>
   function test(blah)
   {
    if (!window.blah)
     window.blah = 0;
    window.blah++;
    document.getElementById(blah).innerHTML = window.blah;
   }
  </script>
 </head>
 <body>
  <div id="first">0</div>
  <input type="button" onclick="test('first')" value="change">
  <br>
  <div id="second">0</div>
  <input type="button" onclick="test('second')" value="change">
  <br>
 </body>
</html> 

The purpose of the code is to have two separate counters - clicking the first button should increment window.first while clicking the second button should increment window.second. How do I phrase this?

1
  • 1
    Use window[blah] instead of window.blah Commented May 22, 2014 at 11:43

1 Answer 1

2

You need to specify the variable name using the square bracket notation:

function test(blah)
{
    if (!window[blah])
        window[blah] = 0;
    window[blah]++;
    document.getElementById(blah).innerHTML = window[blah];
}

Hopefully this gives an idea of how the dot notation works in comparison to the square bracket notation;

var o = {
    key: 'value',
    foo: 'bar'
};

var key = 'foo';

console.log(o['foo']); // 'bar'
console.log(o[key]);   // 'bar'
console.log(o.key);    // 'value'
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, its like an array? Thank you!
@Ulrik No, it's like a map.
@Ulrik In JS, something.blah is the blah member of something, while something[blah] is the member which name is the string in blah.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.