简体   繁体   中英

Using square brackets to concatenate things in Javascript?

Anyone know why this isn't working?

$('#screen').css({
  'background-image': [bg_num == 1 ? 'josh' : 'jessi'] + '_background.jpg',
  'background-color': 'red'
 });

The background color is getting set, but the image is not.

I've not really had much practice using square brackets in Javascript to get this kind of thing done. Anyone have tips if I'm doing something way wrong? Or no of a nice explanation of their use?

EDIT: And just to be clear, the check itself is actually happening, because if I do the same thing in a console.log() is outputs "josh_background.jpg" just fine. It's just not taking in this css setting function.

EDIT:

What you were doing was creating an Array literal with the value 'josh' or 'jessi' , then concatenating '_background.jpg' onto it, so it technically would work.

The issue is that you're missing the 'url()' part of the background-image value.

'background-image': 'url(' + (bg_num == 1 ? 'josh' : 'jessi') + '_background.jpg)',

...but you should still use the () for grouping instead of constructing an Array.


Original answer:

Use parentheses for grouping instead of square brackets:

'background-image': (bg_num == 1 ? 'josh' : 'jessi') + '_background.jpg',

The only use you'll have for square brackets in javascript will be for getting/setting a property on an object, or for creating an Array literal:

var arr = []; // An Array literal

arr[10] = 'someArrValue'; // set index 10


var obj = {};  // A plain object literal

obj['prop'] = 'someObjValue';  // set the "prop" property

var key = 'prop2';

obj[key] = 'someOtherObjValue'; // set the property referenced in the "key" variable

...oh, they have use in regular expression syntax of course...

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