簡體   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