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

176
Visualizações
Javascript: a function returned a value but when I console.log it, always shows undefined

    var testData = [{'date': '10:45', 'electricity': 0.49, 'temp': 49},
            {'date': '11:00', 'electricity': 0.14, 'temp': 50},
            {'date': '11:15', 'electricity': 0.87, 'temp': 35}]
    function findData(time){
        testData.forEach(function(item){
            if(item['date'] == time){
                console.log('item: ', item);
                var result = new Array(item['electricity'], item['temp'])
                console.log('result: ', result)
                return result;
            }
        })
    }
    var a = findData('10:45');
    console.log(a)

Any idea why console.log(a) gives undefined? I have done some research but didn't get the answer:(

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

0

You can not return from a callback for Array#forEach and you need at least a return statment in the function block to get a different value as undefined.

Instead, you could find the object with Array#find, destructure the wanted properties and return an array of values.

function findData(data, time) {
     const result = data.find(({ date }) => date === time);
     if (result) {
         const { electricity, temp } = result;
         return [electricity, temp];
     }
}

var testData = [{ date: '10:45', electricity: 0.49, temp: 49 }, { date: '11:00', electricity: 0.14, temp: 50 }, { date: '11:15', electricity: 0.87, temp: 35 }]

var a = findData(testData, '10:45');
console.log(a)

about 4 years ago · Juan Pablo Isaza Relatório

0

Your function needs to return something. Also, returning something from the forEach() callback won't do it; you have to store that result in a variable that is visible to findData():

function findData(time){
    var r;
    testData.forEach(function(item){
        if(item['date'] == time){
            console.log('item: ', item);
            var result = new Array(item['electricity'], item['temp'])
            console.log('result: ', result)
            r = result;
        }
    })

    return r;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Because you didn't stop the forEach loop after it found result, so the loop keep going to the next index. There are many ways to achieve the result you need. Array.find is one way.

    var testData = [{'date': '10:45', 'electricity': 0.49, 'temp': 49},
            {'date': '11:00', 'electricity': 0.14, 'temp': 50},
            {'date': '11:15', 'electricity': 0.87, 'temp': 35}]
    function findData(time){
        const foundItem = testData.find(function(item){
            return item['date'] == time;
        });
        console.log('item: ', foundItem);
        const result = new Array(foundItem['electricity'], foundItem['temp'])
        console.log('result: ', result) 
        return result;
    }
    var a = findData('10:45');
    console.log(a)

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