1

I want to dynamically initialize a variable array in javascript. I keep getting unexpected token illegal token errors.

in my current script, serviceLimit = 10; but it could be changed at any time.

Attempt #1

var jqSvcPhrase = {};
for(i=1; i<=serviceLimit; i++) {
  jqSvcPhrase[+ i +] = ''; // produces - Uncaught SyntaxError: Unexpected token ]
}

Attempt #2

var jqSvcPhrase = {};
for(i=1; i<=serviceLimit; i++) {
  jqSvcPhrase\[+ i +\] = ''; // produces - Uncaught SyntaxError: Unexpected token ILLEGAL
}

Attempt #3

var jqSvcPhrase = {};
for(i=1; i<=serviceLimit; i++) {
  jqSvcPhrase\\[+ i +\\] = ''; // produces - Uncaught SyntaxError: Unexpected token ILLEGAL
}
2
  • i is integer not string Commented Jan 5, 2015 at 15:35
  • You're not trying to do that in jQuery. You're trying to do that in Javascript... Commented Jan 5, 2015 at 15:36

5 Answers 5

1

i is an integer type, so does not require concatenation. Try this:

var jqSvcPhrase = {};
for (i = 1; i <= serviceLimit; i++) {
      jqSvcPhrase[i] = '';
}
Sign up to request clarification or add additional context in comments.

Comments

1

Uhh... what's with all the +s?

var jqSvcPhrase = {};
for(i=1; i<=serviceLimit; i++) {
  jqSvcPhrase[i] = '';
}

3 Comments

Was simply copying and pasting prior code that worked.
@H.Ferrence Does this means the code was eval'd somewhere? I feel sorry for your code D:
No use of eval but thanks for your sympathies & concerns @aduch :)
1

First of all you are declaring an object and not an array. It should be var jqSvcPhrase = []; instead. Furthermore the + is not needed. It has to be jqSvcPhrase[i]

2 Comments

Objects can still be accessed by index.
"I want to dynamically initialize a variable array [... ]" - you won't he able to use array functions when you got an object. If may be possible but better be careful here
0

Why use curly brackets? Use square brackets for arrays.

var jqSvcPhrase = [];
for(i=1; i<=serviceLimit; i++) {
      jqSvcPhrase[i] = '';
}

Comments

0

Array syntax (Manual ):

[element0, element1, ..., elementN] 
new Array(element0, element1[, ...[, elementN]]) 
new Array(arrayLength)

This should be :

var jqSvcPhrase = new Array(serviceLimit);

and it would make sense to initialize values:

for (x in jqSvcPhrase) { x = ''; }

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.