2016-07-06 85 views
1

我有一個簡單的循環中的Node.js:爲什麼我無法訪問javascript中的對象屬性?

exports.sample = function (req, res) { 
    var images = req.query.images; 
    images.forEach(function (img) { 
     console.log(img); 
     console.log(img.path, img.id); 
     console.log(img); 
    }); 
    res.end(); 
}; 

結果是:

{"id":42,"path":"gGGfNIMGFK95mxQ66SfAHtYm.jpg"} 
undefined undefined 
{"id":42,"path":"gGGfNIMGFK95mxQ66SfAHtYm.jpg"} 

我可以訪問屬性在客戶端而不是在服務器端。

有人可以幫助我瞭解發生了什麼?爲什麼我無法訪問我的對象屬性?

+3

只需檢查它是否是'object'或'string' – Rayon

+1

[解析](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)它也許 ? – Gintoki

+1

在日誌前添加'img = JSON.parse(img)' – imkost

回答

3

正如其他人指出的,最有可能的是img是字符串形式。您需要在其上運行JSON.parse()將其轉換爲對象,以便您可以訪問其屬性。

這裏我在支票內寫了JSON.parse(),即只有當img是「string」類型時才分析它。但是我認爲,你總是會把img當成一個字符串,所以你可以簡單地在沒有檢查的情況下解析它。

exports.sample = function (req, res) { 
    var images = req.query.images; 
    images.forEach(function (img) { 
     console.log(img); 

     //Here, this code parses the string as an object 
     if(typeof img === "string") 
      img = JSON.parse(img); 

     console.log(img.path, img.id); 
     console.log(img); 
    }); 
    res.end(); 
}; 
+0

@Quentin完成。謝謝:) –

+0

這是正確的。我得到一個字符串數組,而不是一個對象數組。謝謝。 – belyid

+0

@belyid你得到一個字符串,而不是一個對象(不是數組);) –

相關問題