1

Here is a sample of what doesn't work:

var array_one = [];
array_one=['a','b','c'];

Declaring and populating the array outside any function doesn't work, but

var array_one = [];
function do_something(){
   array_one=['a','b','c'];
}

does, because it's inside a function. Why?

2
  • 4
    What exactly would you expect that to do? If you intended array_one = ['a','b','c']; you're just missing an =. Or are you trying to refer separately to ['a'], ['b'], and ['c'], changing them to null perhaps? Commented Oct 5, 2011 at 22:34
  • again, my error.. in a real code... there is a '=', i will correct the question, but that will void the answer ! Commented Oct 6, 2011 at 0:06

2 Answers 2

4

What you're doing here is not initialization but instead member lookup. The expression is parsed as array_one[<member name>]. In this case member_name is achieved by evaluating 'a', 'b', 'c'. This uses the comma operator so the 3 expressions are evaluated in order and the result of the expression is the final expression: 'c'. This means your code is effectively doing the following

array_one['c'];

It sounds like what you want is instead

array_one = ['a', 'b', 'c'];
Sign up to request clarification or add additional context in comments.

Comments

2

array_one['a','b','b'] is not syntax to populate an array - I'm not really sure what it does actually.

If you do array_one = ['a','b','c'] then you replace the variable with a new array. (The difference between this and populating an array is that other references to the previous array will still have the old value.)

To add values to the array, use array_one.push('a').

Comments

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.