0

I have created with php several javascript array which are called as follows:

pricesArray_230
pricesArray_350
...etc...

I now want to access these arrays, but I have no clue how to include the dynamic part.

My code right now, which is not working:

newPrice = pricesArray_+productId+[currentSimpleProduct][0];

Where productId is the dynamic part and represents 230, 350, or any other number.

Do any of you have an idea how to dynamically call these arrays?

1
  • Why don't you simply put them in a big (sparse) array or in an object? Commented Aug 14, 2013 at 20:06

3 Answers 3

3

If you're in the browser, and the variable is in the global scope, you can use bracket notation like:

foo = window['pricesArray_'+productId[currentSimpleProduct][0]]
Sign up to request clarification or add additional context in comments.

Comments

3

To avoid eval, assuming that pricesArray_* are global variables, you can use:

window['pricesArray_' + productId][currentSimpleProduct][0]

Better yet, update your dynamically-generated code so it creates an object or array instead of variables:

var pricesArrays = {
    '230': {...},
    '350': {...},
    // etc
}

1 Comment

That's an object actually (not an array) but +1!
1

You have to use eval:

newPrice = eval('pricesArray_' + productId)[currentSimpleProduct][0];

However, eval can be problematic, so I suggest using an object instead. This will require you to change your PHP code to output something like this:

var arrays = {
    product230 : [], // array here
    product350 : [] // array here, etc.
}

Then you can just use:

newPrice = arrays['product' + productId][currentSimpleProduct][0];

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.