我正在尝试创建一个从对象返回所需属性的函数。
对象将如下所示:
export var Characters = [
{
id: 1,
Name: "Abe",
HitPointValue: "124",
StrengthValue: "12",
IntelligenceValue: "14",
WisdomValue: "16",
DexterityValue: "12",
ConstitutionValue: "10",
CharismaValue: "17",
Avatar: require('./images/avatar_7.jpg')
}
]
我试过了:
export function getStat(id, stat) {
var idx = Characters.findIndex((val) => val.id == id);
return Characters[idx].stat;
}
例如,假设我需要获得此对象的“WisdomValue”。
所以我称之为:
<Text style={[styles.stats]}>
{"\n"}
Wisdom Value: {getStat(1, 'WisdomValue')}{"\n"}
</Text>
但我只是得到一个错误'undefined is not object'
如何才能获得一个特定属性,但是以动态方式?所以我不必编写像getHitPointValue(id)这样的separte函数,获取StrengthValue(id)等等......
谢谢!
答案 0 :(得分:2)
使用[]
而不是使用点表示法,因为您尝试通过动态键访问值。
检查此代码段:
var Characters = [
{
id: 1,
Name: "Abe",
HitPointValue: "124",
StrengthValue: "12",
IntelligenceValue: "14",
WisdomValue: "16",
DexterityValue: "12",
ConstitutionValue: "10",
CharismaValue: "17",
}
]
function getStat(id, stat) {
var idx = Characters.findIndex((val) => val.id == id);
if(idx >= 0)
return Characters[idx][stat];
else return "not found"
}
console.log(getStat(1, 'WisdomValue'));
console.log(getStat('15', 'abc'));
&#13;
答案 1 :(得分:1)
var Characters = [
{
id: 1,
Name: "Abe",
HitPointValue: "124",
StrengthValue: "12",
IntelligenceValue: "14",
WisdomValue: "16",
DexterityValue: "12",
ConstitutionValue: "10",
CharismaValue: "17",
}
]
function getStat(id, stat) {
// you can directly find the object rather going through the array index
var character = Characters.find((val) => val.id == id);
// care for non existing characters
if (!character) {
throw new Error(`Character with id ${id} does not exist`);
}
// care for non existing stats
if (!character.hasOwnProperty(stat)) {
throw new Error(`Stat ${stat} is not available for character with id ${id}`);
}
// use the [] notation as opposed to the dot notation when evaluating dynamic property names
return character[stat];
}
console.log(`Wisdom Value: ${getStat(1, 'WisdomValue')}`);
console.log(`Charisma Value: ${getStat(1, 'CharismaValue')}`);
try {
console.log(getStat(2, 'Name'));
} catch (e) {
console.log(e.message);
}
try {
console.log(getStat(1, 'PersuasionValue'));
} catch (e) {
console.log(e.message);
}
&#13;