【问题标题】:Unable to get attribute from object in javascript but can print it to the console when logging its parent无法从 javascript 中的对象获取属性,但可以在记录其父对象时将其打印到控制台
【发布时间】:2014-12-06 21:47:56
【问题描述】:

无法从 javascript 中的对象获取属性,但我可以在记录其父对象时将其打印到控制台。它确实看起来像一个普通的物体。为什么我无法访问_id?

下面的代码在一个函数中:$scope.create = function() { 在我的角度视图中提交表单时被调用:<form class="form-horizontal" data-ng-submit="create()" novalidate>

那么问题来了,在我的函数中创建:

     console.log($scope.account);
      var tmp=$scope.account;
      console.log('id:' +tmp._id);

给我:

      {"user":{"displayName":"David Karlsson","_id":"548217e5402b8b8c194d9c11"},"_id":"5483235cc0d8580000152f0b","__v":0,"created":"2014-12-06T15:40:12.682Z","amount":0,"interests":[{"rate":123,"date":"2014-12-30T23:00:00.000Z","_id":"5483235cc0d8580000152f0c"}],"desc":"","name":"Acount"}

      id:undefined

更改 post 方法没有帮助:

    $scope.create = function() {
        // Create new Income object
      var copy = Object.assign({}, this.account);
      console.log(copy);
    }

给予:

TypeError: undefined is not a function 在 Scope.$scope.create (localhost:3000/modules/incomes/controllers/incomes.client.controller.js:12:29) 在 localhost:3000/lib/angular/angular.js:10880:21 在回调(ocalhost:3000/lib/angular/angular.js:19237:17) 在 Scope.$eval (localhost:3000/lib/angular/angular.js:12788:28) 在 Scope.$apply (localhost:3000/lib/angular/angular.js:12886:23) 在 HTMLFormElement。 (本地主机:3000/lib/angular/angular.js:19242:23) 在 localhost:3000/lib/angular/angular.js:2853:10 在 forEach (localhost:3000/lib/angular/angular.js:325:18) 在 HTMLFormElement.eventHandler (localhost:3000/lib/angular/angular.js:2852:5)

【问题讨论】:

    标签: javascript


    【解决方案1】:

    这是因为在您调用 console.log 之后,但在显示对象之前,一些代码更改了 $scope.account

    例如:

    var obj = {prop: {}};
    console.log(obj.prop);   // Produces {foo: "bar"}
    var cached = obj.prop;
    console.log(cached.foo); // Produces undefined
    obj.prop.foo = 'bar';
    

    缓存值不会发生这种情况,因为它是字符串而不是对象。

    要修复它,您可以使用 EcmaScript6 Object.assign 来“复制”您的对象:

    var obj = {prop: {}};
    console.log(Object.assign({}, obj.prop)); // Produces {}
    var cached = obj.prop;
    console.log(cached.foo);                  // Produces undefined
    obj.prop.foo = 'bar';
    

    【讨论】:

    • 好吧,也许我遗漏了一些东西,但你的第一个例子对我来说毫无意义。你在哪里运行的?
    • 现在我更加困惑了。第一个控制台日志应该记录一个空对象......控制台日志不是同步的吗?我点击了几次运行,我得到了这个puu.sh/dkSHk/6d5fd88601.png
    • @ionutvmi 它是异步的,至少在 Firefox 37 上是这样。
    • 在 firefox 上我总是得到你发布的内容,但在 firebug 中我总是在第一个控制台日志上得到一个空对象...该屏幕截图来自 chrome 40
    • 好的,所以它在 chrome 中也是异步的,谢谢你的回复
    猜你喜欢
    • 1970-01-01
    • 2017-04-16
    • 2014-10-24
    • 1970-01-01
    • 2023-01-14
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多