【问题标题】:Why is this undefined为什么这是未定义的
【发布时间】:2015-02-03 17:52:19
【问题描述】:

为什么这是无效/未定义的??

我的查询:

            $scope.timesheets = Sign.query({
            projectId: $scope.selected.project[0],
            startWeek: this.weekStart,
            endWeek: this.weekEnd
        });

        console.log($scope.timesheets);

        console.log($scope.timesheets.sig);

        console.log($scope.timesheets[0].sig);

    };

我的控制台日志返回:

console.log($scope.timesheets);

返回时间表数组

[
    {
        "_id": "54d104718c54c8202654d6cd",
        "__v": 0,
        "sig": "ass...", 
......

但是当我使用 console.log(...[0]).sig 它返回:

TypeError: 无法读取未定义的属性 'sig'

console.log(...sig) 返回未定义

为什么我无法获得时间表[0].sig?

【问题讨论】:

  • 控制台很可能在欺骗你,因为console.log($scope.timesheets); 最初不包含该数组,但在异步操作完成后会包含该数组,并且由于您没有在控制台直到它完成之后,它会在完成之后而不是之前显示值。该数组通过引用传递给控制台,但第二个两个 console.logs 中的未定义值不是。
  • console.log($scope.timesheets[0].sig);
  • @KevinB console.log($scope.timesheets[0].sig);
  • 当你只是在安慰 console.log($scope.timesheets[0]);
  • 当你输出console.log($scope.timesheets.length)时它会说什么

标签: javascript database angularjs rest variables


【解决方案1】:

看起来您的 Sign 对象是 $resource,这意味着 $scope.timesheets 是一个资源对象,其中包含一个在从服务器返回时将被解析的承诺。试试这个:

$scope.timesheets.$promise.then(function (timesheets) {
    console.log(timesheets[0].sig);
});

Sign.query({ /* ... props ... */}, function (timesheets) {
    console.log(timesheets[0].sig);
});

您能够使用console.log($scope.timesheets) 的原因是因为它记录了对该对象的引用,当您在控制台中查看它时,该引用已解决。但是,尝试在对象上记录属性将解析为 undefined,直到响应从服务器返回。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-05
    • 2013-09-13
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    相关资源
    最近更新 更多