繁体   English   中英

如何访问在运行时添加到对象的属性?

[英]How do I access a property that I added during runtime to an object?

在此处输入图片说明

在这个例子中,我向对象添加了属性“col_id_3”。 后来我想访问它。 尽管我可以看到属性“col_id_3”在那里(见图),但我无法使用Object.col_id_3访问它。 JavaScript 返回undefined 我该如何访问它? 如何使该属性“粘”到对象上?

myFunction: function(){
      return db.allDocs({include_docs: true}, function(err, response) {
        var myArray =[];
        if(err) {
          console.log(err);
          throw new Error(console.error("error"));
        } else {

          return Promise.all(response.rows.map(function(row){           
            if(row.doc.type == 'myAttribute') {
              row.myNewlyAddedProperty = {id: row.doc._id,
                name: row.doc.data.name,
                isValid: false
              };

              myAsynchFunction(row.qc)
              .then(anotherAsynchFunction(row.qc), function(error) {
                console.error("handle error: "+error.stack);
                throw error;
              })
              .catch(function(error) {
                console.error("handle error in catch case: "+error.stack);
              });
            }
          }));
        }
      })
      .then(function (arrayResults) {
        var onlyFilteredResults = [];
        for (var i = 0; i < arrayResults.rows.length; i++){
          var changedInput = arrayResults.rows[i];
          if (arrayResults.rows[i].doc.type == 'myAttribute') {
            console.log(changedInput); // here I can see my newly add Attribute
            console.log(changedInput.myNewlyAddedProperty); // here I can't access my newly attribute anymore
            console.log(Object.keys(changedInput)); //here my newly added Attribute isn't listed

          }

console.log显示对象在扩展时的状态,而不是在日志时。 因此, changedInputmyNewlyAddedProperty当时您单击展开记录的对象,而不是当你真正做了log通话。

您的问题是您同时使用db.allDocs的回调和承诺。 假设您在这里使用 PouchDB,在回调运行之前承诺结果:

db.allDocs({}, function() { console.log("callback"); })
  .then(function() { console.log("promise") })

此代码将首先记录"promise" ,然后记录"callback" 因此,您的.then(function (arrayResults) { ... })db.allDocs(..., function(err, response) { ... })回调之前运行。 这里的解决方案是不要对allDocs使用回调, allDocs使用承诺:

db.allDocs(...)
.then(function(response) {
    var myArray =[];
    ...
    return response;
})
.then(function (arrayResults) {
    var onlyFilteredResults = [];
    ...
});

此外,您的response.rows.map回调不返回任何值,因此Promise.all获取undefined值的数组。 我假设您想return myAsynchFunction(row.qc).then(...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM