简体   繁体   中英

Trouble setting JavaScript variable of object using ternary operator

Hi Guys I'm having trouble trying to set a variable (val) to be one of 2 possible object attributes. The below code explains what I'm trying to do.

function myFnct(elem, imgSrcType) {
  var val = imgSrcType == "bg" ? elem.style.backgroundImage : elem.src;  
  val  = 'image.jpg'  
}

I'm using a ternary operator to try and avoid having to write:

if (imgSrcType === "bg") {
    elem.style.backgroundImage = "url('image.jpg')";
}
else {
    elem.src = "image.jpg";
}

Basically the 'val' variable is not getting set correctly as I guess its something to do with elem object. I'm trying to avoid using the if statement as I will need to use it a few times within the function. And I'm trying to keep is as DRY as possible.

Any help getting it to work with the ternary operator method would be awesome!

if (imgSrcType === "bg") {
    elem.style.backgroundImage = "url('image.jpg')";
}
else {
    elem.src = "image.jpg";
}

ugly but working rewrite:

void (
      imgSrcType === 'bg' 
        && (elem.style.backgroundImage = "url('image.jpg')")
        || (elem.src = "image.jpg") 
);

Equals:

void (
      imgSrcType === 'bg' 
        ? (elem.style.backgroundImage = "url('image.jpg')")
        : (elem.src = "image.jpg") 
);

So by adding parentheses ( elem.src = "image.jpg" ) you can do the assignment. You can also use a comma to return something in a value assignment.

Using this knowledge, you could rewrite myFnct :

function myFnct(elem, imgSrcType) {
  var val = ( 
              void( imgSrcType == "bg" 
                     ? (elem.style.backgroundImage = "url('image.jpg')") 
                     : (elem.src = "image.jpg") ), //<= ternary done - comma
              'image.jpg' 
            );  
   //now val = 'image.jpg'
}

Note : this is all about what is possible . If you need/want to keep your code readable, using the if ... else statement is the better option.

Ternary operations can only assign their outcome to a single variable. They are useful if you are setting that single variable to different values depending on the result of a boolean expression. Since you are trying to assign the image URL to either the background-image or to the source, you cannot use a simple ternary operation. The other answers are using pretty complex/quasi-obfuscated code to accomplish what could be done with a simple if/else statement. Your code - especially for such a simple operation - should be easy to read. So, I recommend just sticking with the following:

function setImage(elem, imgSrcType)
{
    var imgURL = "image.jpg";

    if(imgSrcType == "bg")
    {
        elem.style.backgroundImage = "url('" + imgURL + "')";
    }
    else
    {
        elem.src = imgURL;
    }
}

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