[英].reduce() not returning array in javascript
I wrote a function that takes in parsed JSON from a XML request, it works when I use forEach() so I wanted to use reduce() to push what I could do with JS.我编写了一个从 XML 请求接收解析 JSON 的函数,当我使用 forEach() 时它可以工作,所以我想使用 reduce() 来推动我可以用 JS 做的事情。 What am I doing wrong?
我究竟做错了什么?
forEach function: forEach 函数:
function whatTemp48h(response){
var data;
data = response ;
var temp = [];
data.hourly.data.forEach(function(el,inx){
temp.push(el.apparentTemperature)
})
console.log(temp)
return temp;
}
Reduce function:减少功能:
function gimmeThaTemps(res){
return res.hourly.data.reduce(function(accu,el,c){
accu.push(el.apparentTemperature);
return accu;
},[]);
}
it doesent return anything when I use reduce.当我使用reduce时它不会返回任何东西。 I am using an AJAX call to return some parsed JSON and im calling the AJAX function and sending it a call back.
我正在使用 AJAX 调用返回一些已解析的 JSON,我正在调用 AJAX 函数并向其发送回调。
function getWeather(lat,long, cb){
var xhr = new XMLHttpRequest();
var response;
xhr.open('GET','https://api.darksky.net/forecast/'+api_KEY+'/'+lat+','+long,true);
xhr.onload = function() {
// console.log(this.responseText)
// console.log(JSON.parse(this.responseText));
cb(JSON.parse(this.responseText));
};
xhr.onerror = function() {
console.log("Connection error");
};
xhr.send();
}
when I call I do当我打电话时
var reqReturn = getWeather(decodeMTL.lat,decodeMTL.long,gimmeThaTemps)
console.log(reqReturn);
Sorry for the newbish question but im still learning JS.对于新手问题很抱歉,但我仍在学习 JS。 Ps I have a XMLhttpprerequest node npm to run it in my command line.
Ps 我有一个 XMLhttpprerequest 节点 npm 可以在我的命令行中运行它。
A bit off-topic, what you are looking for is probably function map
:有点题外话,您正在寻找的可能是 function
map
:
return res.hourly.data.map(function(el) { return el.apparentTemperature; });
Or with lambda:或者使用 lambda:
return res.hourly.data.map(el => el.apparentTemperature);
My code is wrong.我的代码是错误的。 I was returning inside a callback, therefore it was returning nowhere!!!
我在回调中返回,因此它无处返回!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.