Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

70
Visualizações
Get a default value instead of `undefined` for non-existing array element

I'm trying to get the value "0" back when there's nothing written in the spreadsheet cell whose data I get returned as JSON in an API call. But the output is always undefined. I tried using if else, but it didn't work.

IMG SHEET

$(function() {
  $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/10Ct44JBW-CyoApJXIV87jeVU3Rr-fiLTdoTIJdbSwG8/values/page!A1:C3?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
    $.each(result.values, function(i, field) {
      $(".guide").append('<span class="field1">' + field[0] + '</span><br><span class="field2">' + field[1] + '</span><br><span class="field3">' + field[2] + '</span><br>');
    });
  });
});
.field1 {
  font-size: 12px;
  color:green;
}
.field2 {
  font-size: 14px;
  color:blue;
}
.field3 {
  font-size: 18px;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="guide"></div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the ?? operator (Nullish coalescing operator) to replace null and undefined with something else, in this case, 0.

For example: (field[1] ?? 0)

$(function() {
  $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/10Ct44JBW-CyoApJXIV87jeVU3Rr-fiLTdoTIJdbSwG8/values/page!A1:C3?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
    $.each(result.values, function(i, field) {
      $(".guide").append('<span class="field1">' + (field[0] ?? 0) + '</span><br><span class="field2">' + (field[1] ?? 0) + '</span><br><span class="field3">' + (field[2] ?? 0) + '</span><br>');
    });
  });
});
.field1 {
  font-size: 12px;
  color: green;
}

.field2 {
  font-size: 14px;
  color: blue;
}

.field3 {
  font-size: 18px;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="guide"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda