为什么我不能在javascript中访问对象属性?
我在node.js中有一个简单的循环:
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"}
我可以访问客户端的属性,但不能访问服务器端的属性。
有人可以帮助我了解发生了什么? 为什么我不能访问我的对象属性?
正如其他人所指出的,最有可能的img
是以stringforms。 您需要在其上运行JSON.parse()
以将其转换为对象,以便可以访问其属性。
在这里,我已经写了JSON.parse()里面的检查,即只有当img
是“string”types时,你应该parsing它。 但是我认为,你总是会得到一个stringimg
,所以你可以简单地parsing它,而不用检查。
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(); };