How to use ternary operator to determine what to display?

Asked

Viewed 681 times

1

How can I correctly use the Ternary Operator in Javascript. I have the following code:

var Requisitar = function(){
    setTimeout(function(){
        $.ajax({
        url: 'https://steamgaug.es/api/v2', // Acesso direto a API
        success: function(resposta){ // <-- variavel resposta vem com todos dados da API
            // Steam Loja Comunidade
            $("#dota2-statusapidota").html(resposta["IEconItems"]["570"]["online"]);
        }
        });
    Requisitar();
    },5000);//1000=a um segundo, altere conforme o necessario
};
Requisitar();//Dispara

So When Used in HTML:

li id="dota2-statusapidota" < /li >

The value shown is 1.

How can I use the ternary operator correctly so that this "1" is displayed as "Online"?

JSON Recebido:

{
    "ISteamClient": {
        "online": 1
    },
    "SteamCommunity": {
        "online": 1,
        "time": 25,
        "error": "No Error"
    },
    "SteamStore": {
        "online": 1,
        "time": 2,
        "error": "No Error"
    },
    "ISteamUser": {
        "online": 1,
        "time": 20,
        "error": "No Error"
    },
    "IEconItems": {
        "440": {
            "online": 1,
            "time": 27,
            "error": "No Error"
        },
        "570": {
            "online": 1,
            "time": 27,
            "error": "No Error"
        },
        "730": {
            "online": 1,
            "time": 27,
            "error": "No Error"
        }
    },
    "ISteamGameCoordinator": {
        "440": {
            "online": 1,
            "schema": "http://media.steampowered.com/apps/440/scripts/items/items_game.b7f5e5dded37fbd6494d96690a71e507d28279f7.txt",
            "error": "No Error",
            "stats": {
                "spyScore": "0",
                "engiScore": "0"
            }
        },
        "570": {
            "online": 1,
            "error": "No Error",
            "stats": {
                "players_searching": 20509
            }
        },
        "730": {
            "online": 1,
            "error": "No Error",
            "stats": {
                "players_searching": 2310,
                "players_online": 111128
            }
        }
    }
}
  • Highly related: http://answall.com/questions/4907/differtes-formas-de-if-e-else, http://answall.com/questions/10539/o-que-significa-e-dentro-de-uma-express%C3%A3o? lq=1

1 answer

4


Thus:

var online = resposta["IEconItems"]["570"]["online"];
$("#dota2-statusapidota").html(online === 1 ? "online" : "offline");

I put the original data in a variable to make it easier to read. The operator’s use is simple: if online for 1, the expression returns the string "online", else it returns "offline".

A ? B : C;
    ^   ^
    |   retornado se A não for verdadeiro
    |
    retornado se A for verdadeiro

Browser other questions tagged

You are not signed in. Login or sign up in order to post.