为什么这是无效/未定义的??
我的查询:
$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: Cannot read property 'sig' of undefined
console.log(...sig) 返回未定义
为什么我无法获取时间表[0].sig?
最佳答案
看起来您的 Sign 对象是 $resource ,这意味着 $scope.timesheets 是一个包含 promise 的资源对象,该 promise 将在从服务器返回时得到解析。试试这个:
$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)
的原因是它正在记录对对象的引用,该引用在您查看它时已解析在你的控制台中。但是,尝试记录对象的属性将解析为未定义
,直到服务器返回响应为止。
关于javascript - 为什么这是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28305494/