我有这样的javascript代码
for (let x = 0; x < result.data.length; x++) {
let tankMaterial = await readTank(result.data[x].tank_id);
console.log(JSON.stringify(tankMaterial));
parseObj[x] = {
tank_id: result.data[x].tank_id,
tank_name: result.data[x].tank_name,
temperature: result.data[x].temperature,
level_percent: Number.parseFloat(scale(result.data[x].pressure)).toFixed(2),
level_raw: result.data[x].pressure,
level_metric: (result.data[x].pressure * 6894.76) / (1000 * 9.8),
};
}console.log的结果是:
{"id_material":"1","height":50,"diameter":25,"name":"CPO"}我尝试从"tankMaterial“对象中提取"name”属性值,代码如下:
for (let x = 0; x < result.data.length; x++) {
let tankMaterial = await readTank(result.data[x].tank_id);
console.log(JSON.stringify(tankMaterial.name));
parseObj[x] = {
tank_id: result.data[x].tank_id,
tank_name: result.data[x].tank_name,
temperature: result.data[x].temperature,
level_percent: Number.parseFloat(scale(result.data[x].pressure)).toFixed(2),
level_raw: result.data[x].pressure,
level_metric: (result.data[x].pressure * 6894.76) / (1000 * 9.8),
};
}但它总是会犯错误
TypeError: Cannot read property 'name' of undefined
at TankData (/var/www/html/demo1/api/TankData.js:20:43)我一直试图从tankMaterial对象访问另一个属性,但是结果总是一样的。
为什么我不能访问tankMaterial对象的值?
发布于 2021-04-28 14:47:14
let parseObj = [];
async function test(result) {
for (let index = 0; index < result.data.length; index ++) {
currentValue = result.data[index]
// for (let currentValue of result.data) { can be used for good reading but 'continue' cannot be used
let tankMaterial = await readTank(currentValue.tank_id).catch(() => {
console.error('This promise failed')
continue; // continue to next loop if some error in loop
});
console.log(tankMaterial) // this will be undefined if your promise has failed and you //if u don't use continue and start parsing/stringify it will throw you an error
try {
console.log(tankMaterial.name)// if tankMaterial is undefined then u will get 'Cannot read property 'name' of undefined'
} catch (error) {
console.log(error) // log the error in case failure in your case name is not property of undefined
}
console.log(tankMaterial);// {"id_material":"1","height":50,"diameter":25,"name":"CPO"}
parseObj[index] = {
tank_id: currentValue.tank_id,
tank_name: currentValue.tank_name,
temperature: currentValue.temperature,
level_percent: Number.parseFloat(scale(currentValue.pressure)).toFixed(2),
level_raw: currentValue.pressure,
level_metric: (currentValue.pressure * 6894.76) / (1000 * 9.8),
};
}
}发布于 2021-04-28 11:54:36
您需要执行JSON.parse(tankMaterial).name来访问它。
https://stackoverflow.com/questions/67299702
复制相似问题