Passing a Variable into a String which is being pushed into an existing Array
I am attempting to pass a variable into a string while the string itself is being pushed into an existing array like so:
var myVar = 'slug';
myArray.push(['item one', '/path/to/' + myVar + '/']);
This is not working at all. I can see the proper value get assigned to myVar
; however, the myVar
in the array is not even recognized as a variable.
This seems easy enough, but I'm obviously missing something.
Thanks for your help.
EDIT: Not a Javascript problem after all.
As Alex demonstrated, this definitely normally works. (And yes, this is an existing array.)
However, I neglected to mentio开发者_运维技巧n that the push method is wrapped in bit of Django templating logic to have it only run on my dev instance, like thus:
{% ifequal INSTANCE 'DEVELOPMENT' %]
myArray.push(['item one', '/path/to/' + myVar + '/']);
{% endifequal %}
I didn't mention the logic because I didn't see how it could be interfering. I had confirmed that:
- everything with the logic was behaving as expected
- the INSTANCE did in fact equal 'DEVELOPMENT'
- and that line of Javascript was visible in the source, which wouldn't be the case if the logic was misbehaving.
However, if I remove that Django logic, everything with the Javascript works as desired.
For some reason, this server-side logic is preventing me from passing any external values into the array, client- or server-side.
As an experiment, I tried this...
myArray.push(['item one', '/path/to/{{ block slug }}undefined{{ endblock }}/']);
...with the following in a child template.
{{ block slug }}slug{{ endblock }}
The same thing happens. With the template logic in place, the value is /path/to/undefined
. Without it, the value is /path/to/slug
as desired.
Why this is happening is a mystery to me. I can work around it, but if anyone has any thoughts, I'd love to hear them.
Thanks again.
Noob side question: what's SO etiquette about altering post titles?
It definitely works.
Perhaps you meant to concatenate the Array
instead, with concat()
? At the moment you are pushing a new Array
onto the existing Array
as a member, resulting in a multi dimensional Array
.
I also assumed myArray
already pointed to an Array
. If not, just do var myArray = []
.
You need to instantiate the array before using the push method:
var myVar = 'slug';
var myArray=new Array();
myArray.push(['item one', '/path/to/' + myVar + '/']);
What is not working?
You are creating an array within an array.
You need to access the new arrays elements like this:
myArray[0][1] // this is "/paht/to/slug/
Re-reading your comments it sounds like you are trying to access a property of the array:
myArray.myVar
In javascript if you want to have a named element you need to use an object.
myObject = {};
myObject.myVar = "/path/to/slug/";
alert(myObject.myVar) // "/path/to/slug/"
Or you can add it directly to the array as a property:
myArray.myVar = "/path/to/slug/";
alert(myArray.myVar);
精彩评论