Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript无法读取属性';forEach&x27;取数后未定义的值_Javascript_Arrays_Foreach - Fatal编程技术网

Javascript无法读取属性';forEach&x27;取数后未定义的值

Javascript无法读取属性';forEach&x27;取数后未定义的值,javascript,arrays,foreach,Javascript,Arrays,Foreach,我试着看其他问题,但找不到合适的解决办法。我检索一个GET响应,并将其存储到一个变量中,然后在该数组中查找每日发生的事件。代码可以工作,但一旦到达forEach,它就会抱怨: Cannot read property 'forEach' of undefined 。这是我的密码: var myObj; fetch('https://blashblashblash.com?param1') .then(res=>res.json()) .then(data=>myObj= data)

我试着看其他问题,但找不到合适的解决办法。我检索一个GET响应,并将其存储到一个变量中,然后在该数组中查找每日发生的事件。代码可以工作,但一旦到达forEach,它就会抱怨:

Cannot read property 'forEach' of undefined
。这是我的密码:

var myObj;
fetch('https://blashblashblash.com?param1')
.then(res=>res.json())
.then(data=>myObj= data)
.then(() => console.log(myObj));

var myRes = [];

myObj.forEach(function (elem) {
    var date = elem.CreationDate.split(' ')[0];


    if (myRes [date]) {
        myRes [date] += 1;
    } else {
        myRes [date] = 1;
    }
});
这就是myObj完成后的内容:

[{Id, Var1, Var2, CreationDate},
{1, 123, Var2, 2020-12-11},
{2, 1234, Var2, 2020-12-12},
{3, 12345, Var2, 2020-12-12},
{4, 1234, Var2, 2020-12-13},
{5, 321, Var2, 2020-12-15},
{6, 3214, Var2, 2020-12-15},
{7, 5432, Var2, 2020-12-16}]
我错在哪里?如果我在不同的步骤中执行代码,它会正常工作

编辑: 以下是我的更新代码:

var myObj;
var myRes= [];
fetch('https://blashblashblash.com?param1')
.then(res=>res.json())
.then(data=>myObj= data)
.then(() => {
myObj.forEach(function (elem) {
    var date = elem.CreationDate.split(' ')[0];
    if (myRes[date]) {
        myRes[date] += 1;
    } else {
        myRes[date] = 1;
    }
});

});

var finalResult= {};
dates.forEach(date => {
    if(!myRes.hasOwnProperty(date)) {
        finalResult[date] = 0;
    } else {
        finalResult[date] = myRes[date];
    }
    return finalResult;
});

如果我执行整个,我的finalResult是空的,而如果我在块中执行它,它会工作。如果我将myRes=[]插入到最后一个中,那么它会抱怨找不到它。我哪里错了?

因为您的fetch&then是一个异步操作,所以您需要执行forEach in then函数,如下所示:

var myObj;
fetch('https://blashblashblash.com?param1')
.then(res=>res.json())
.then(data=>myObj= data)
.then(() => {
    console.log(myObj);
    var myRes = [];

    myObj.forEach(function (elem) {
        var date = elem.CreationDate.split(' ')[0];


        if (myRes [date]) {
            myRes [date] += 1;
        } else {
            myRes [date] = 1;
        }
    });
});

由于fetch&then是一个异步操作,因此需要在then中执行forEach函数,如下所示:

var myObj;
fetch('https://blashblashblash.com?param1')
.then(res=>res.json())
.then(data=>myObj= data)
.then(() => {
    console.log(myObj);
    var myRes = [];

    myObj.forEach(function (elem) {
        var date = elem.CreationDate.split(' ')[0];


        if (myRes [date]) {
            myRes [date] += 1;
        } else {
            myRes [date] = 1;
        }
    });
});
编辑 重复:你可能更喜欢

编辑:从
then()外部访问响应
简短答复:
你不能。

长答覆: 您所做的是一个异步操作。这意味着我们不知道需要多长时间

给出下面的示例代码,假设
fetch()
需要5秒钟才能完成

fetch('https://blashblashblash.com?param1)。然后(其他事情);
someTaskAfterFetch();
console.log('Done');
运行此代码后,需要多长时间才能在控制台中看到“完成”?答案是立即

发生了什么事? 让我们看看会发生什么

    ===       fetch(url).then(doOtherThings) --> 'Start' fetching, without waiting for result.
     |               |
     |               |                       --> You expect fetch to be done here, which will not happen.
     |               |
     |        someTaskAfterFetch()           --> At this moment you see no fetch result.
almost 0 sec         |
     |               |
     |        console.log('Done')
     |               |
    ===       'Done' is printed
     |               |
     |               |
about 5 sec   (in some future)
     |               |
     |               |
    ===       **Fetch completed**             --> Fetch is finished here.
                     |
              doOtherThings(result)           --> doOtherThings, which we passed to `then()` will be run here.
执行从
fetch(url)开始,然后在第1行执行(doOtherThings)

然后,立即继续在第2行执行
someTaskAfterFetch()

紧接着,移动到
console.log('done')

在不久的将来(大约5秒钟之后),您开始的获取最终完成,并使用结果调用
doOtherThings

如何处理结果? 在考虑异步任务时,必须将调用和等待分开。您通过调用
fetch()
启动了提取任务,但没有等待结果

要处理提取结果,请执行以下操作:

  • 您可以等到任务完成()
  • 或者告诉您在获取完成时要做什么
使用
then()
是第二种方法。您可以将所有结果处理代码传递到
then()

要获得更详细的答案,您可能会喜欢


在代码中

fetch('https://blashblashblash.com?param1')
.then(res=>res.json())
.然后(数据=>myObj=数据)
.然后(()=>console.log(myObj));
这条线将立即返回

就在那之后,

myObj.forEach(函数(elem){
var日期=要素创建日期分割(“”)[0];
如果(myRes[日期]){
迈尔斯[日期]+=1;
}否则{
迈尔斯[日期]=1;
}
});
将调用forEach的
forEach

此时,请求获取作业会在
forEach
之前快速完成。但是,获取本身在当时可能还没有完成

传递给以下
then()
调用的函数将在获取成功完成后启动

您可以将
forEach
代码传递给
then()
方法:

var-myObj;
取('https://blashblashblash.com?param1')
.then(res=>res.json())
.然后(数据=>myObj=数据)
.然后(()=>console.log(myObj));
.然后(()=>{
var-myRes=[];
myObj.forEach(函数(元素){
var日期=要素创建日期分割(“”)[0];
如果(myRes[日期]){
迈尔斯[日期]+=1;
}否则{
迈尔斯[日期]=1;
}
});
//还有其他与myRes有关的事情。
})
编辑 重复:你可能更喜欢

编辑:从
then()外部访问响应
简短答复:
你不能。

长答覆: 您所做的是一个异步操作。这意味着我们不知道需要多长时间

给出下面的示例代码,假设
fetch()
需要5秒钟才能完成

fetch('https://blashblashblash.com?param1)。然后(其他事情);
someTaskAfterFetch();
console.log('Done');
运行此代码后,需要多长时间才能在控制台中看到“完成”?答案是立即

发生了什么事? 让我们看看会发生什么

    ===       fetch(url).then(doOtherThings) --> 'Start' fetching, without waiting for result.
     |               |
     |               |                       --> You expect fetch to be done here, which will not happen.
     |               |
     |        someTaskAfterFetch()           --> At this moment you see no fetch result.
almost 0 sec         |
     |               |
     |        console.log('Done')
     |               |
    ===       'Done' is printed
     |               |
     |               |
about 5 sec   (in some future)
     |               |
     |               |
    ===       **Fetch completed**             --> Fetch is finished here.
                     |
              doOtherThings(result)           --> doOtherThings, which we passed to `then()` will be run here.
执行从
fetch(url)开始,然后在第1行执行(doOtherThings)

然后,立即继续在第2行执行
someTaskAfterFetch()

紧接着,移动到
console.log('done')

在不久的将来(大约5秒钟之后),您开始的获取最终完成,并使用结果调用
doOtherThings

如何处理结果? 在考虑异步任务时,必须将调用和等待分开。您通过调用
fetch()
启动了提取任务,但没有等待结果

要处理提取结果,请执行以下操作:

  • 您可以等到任务完成()
  • 或者告诉您在获取完成时要做什么
使用
then()
是第二种方法。您可以将所有结果处理代码传递到
then()

要获得更详细的答案,您可能会喜欢


在代码中

fetch('https://blashblashblash.com?param1')
.then(res=>res.json())
.然后(数据=>myObj=数据)
.然后(()=>console.log(myObj));
这条线将立即返回

就在那之后,

myObj.forEach(函数(elem){
var日期=要素创建日期分割(“”)[0];
如果(myRes[日期]){
迈尔斯[日期]+=1;
}否则{
迈尔斯[日期]=