简体   繁体   中英

Concatenating strings with variables inside a javascript array property

I understand that this probably isn't something I should be making a habit of. But I was trying to concat a variable to a string that's stored in as a Javascript array property.

For instance I have:

var form = {
    'var1' : 'has a value here',
    'array' : [
        [ 'some text', 'some more text' ],
        [ 'second line of text', 'second entry ' + form.var1]
    ]
};
alert( form.array[1][1] );

That results in an alert displaying 'undefined'.

If I instead do this:

var var1 = 'has a value here';
var form = {
    'array' : [
        [ 'some text', 'some more text' ],
        [ 'second line of text', 'second entry ' + var1 ]
    ]
};
alert( form.array[1][1] );

The string is defined and displays properly.

Is there a way I can store that value under the 'form' object and still get the result I want? I'm presuming 'no'. But I figured I'd ask. (This is a difficult question to google. :P)

You can't do it inside the object literal (before finishing the object expression, the form is undefined.), but you could do it outside.

var form = {
    'var1' : 'has a value here',
    'array' : [
        [ 'some text', 'some more text' ],
        [ 'second line of text', 'second entry ']
    ]
};

form.array[1][1] += form.var1;
alert( form.array[1][1] );​

You could declare it in two parts:

var form = {
    'var1' : 'has a value here'
};

form['array'] = [
    [ 'some text', 'some more text' ],
    [ 'second line of text', 'second entry ' + form.var1]
];

alert( form.array[1][1] );

I am surprised you even reach the alert statement. Your code would fail as soon as it hits form.var1 since form is not defined. One way to get to that is to define them separately. Like so

var form = {};
   form.var1 = 'has a value here';
   form.array =   [
      [ 'some text', 'some more text' ],
      [ 'second line of text', 'second entry ' + form.var1]
   ];  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM