1

I am learning Javascript. I wrote a JS to return a Json-type value.

  var generateUrl = function(Name, Letter, rootUrl, V1) {
  rootUrl = rootUrl || Letter;
  return  {
    classname: 'mycss-' + Letter,
    text: Name,
    url: rootHref.replace(Rex, "$1" + rootUrl + "."),
    onclick: {
      fn: clickFn,
      obj: V1
    }
  };
};

I want to add a if statement inside url:. For example, if Name = google, url won't use this logic rootHref.replace(Rex, "$1" + rootUrl + "."), instead it will directly return an url. I have searched for an answer quite a while but still have no luck. May someone tell me how to add a if statement logic in my code.

2
  • 3
    Use the ternary operator instead. Commented Oct 26, 2017 at 20:58
  • 3
    That thing you're returning is called an object literal, nothing to do with JSON. You can't put much logic into an object literal, but you can assign it to a variable and then use bracket or dot notation to assign a new property value (eg if (thing == "google") myObj.url = "google-specific URL";) Commented Oct 26, 2017 at 21:00

1 Answer 1

4

Try as follows

 url: (num == 1) ? Link1 : Link2,
Sign up to request clarification or add additional context in comments.

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.