-3

I am new to javascript and I am having this really simple problem.

    var counters = [];
    for (var i = 0; i < 3; i++) {
        counters.push[i];
    }
    alert(counters.length);

This code is expected to alert 3, but the real result is 0. Can someone please this to me. I'm not really sure how to ask about this error. Thanks

Sorry for this question.. I have fixed it. Thanks for answering

I can't ask another quesition yet since not enough karma.. But My real problem is this

for (var i = 0; i < 2; i++) {
if (i == 1) {document.write(" <tr class='noBorder' onclick='alert(i)');} 
if (i == 0){ document.write(" <tr class='noBorder' onclick='alert(i)');}
}

Whenever I click on a row, the alert results in 2. It's basically this question, but in html Passing parameter onclick, in a loop

1
  • 1
    [] is for access elements of an array, () is for method invocation. Commented Mar 31, 2017 at 19:04

2 Answers 2

2

If you are pushing into an array then you need to push the value, The syntax is: array.push(value).

The correct way would be:

    var counters = [];
    for (var i = 0; i < 3; i++) {
        counters.push(i);
    }
    alert(counters.length);

Sign up to request clarification or add additional context in comments.

Comments

1
counters.push[i];

is supposed to be

counters.push(i);

or

counters[i] = i;

() is used for method invocation. push is a method available for all objects of type array, so in this case you are supposed to use () to add values to the array.

[] is used to access a ( named dynamic ) property on a object.

var obj = {
   a : 10,
   c : function() {
       return 20;
   } 
};

In the above use case to access the values of a and b, you would use . or [] to access the properties of the object.

obj.a  || obj['a'];
obj.b()  || obj['b']();

Because property c is a function, you would first access the property using [] and then call the function using ()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.