问题描述
所以我学习 JS 还不到 1 周,我一直在努力寻找解决方案,但除了涉及函数和与 JSON.stringify(我不明白)有关的答案之外,我似乎无法找一个。我想使用模板文字来显示来自每个属性的特定信息,而不是在迭代此对象时使用字符串连接。这可能吗?
pokemonList = [
{name: 'Bulbasur',height: 70,weight: 15.2,type: ['grass','poison']},{name: 'Charmander',height: 60,weight: 18.7,type: ['fire']},{name: 'Squirtle',height: 50,weight: 19.8,type: ['water']}
];
for (let i=0; i < pokemonList.length; i++) {
console.log(`${pokemonList.name[i]} ${pokemonList.height[i]}`);
};
解决方法
你在 for 循环中有错误
您应该将 [i] 替换为 pokemontList,而不是 pokemonList 的属性 ${pokemonList[i].name} ${pokemonList[i].height}
你绝对可以!您只需要将 pokemonList.name[i]
更改为 pokemonList[i].name
。
pokemonList
是其中包含元素的元素,因此您可以使用 pokemonList[i]
访问其中的元素,然后 pokemonList[i].name
将为您提供该元素的 name 属性。
这是固定代码:
pokemonList = [
{name: 'Bulbasur',height: 70,weight: 15.2,type: ['grass','poison']},{name: 'Charmander',height: 60,weight: 18.7,type: ['fire']},{name: 'Squirtle',height: 50,weight: 19.8,type: ['water']}
];
for (let i=0; i < pokemonList.length; i++) {
console.log(`${pokemonList[i].name} ${pokemonList[i].height}`);
};
JSON.stringify
会将整个对象打印为一个字符串,它看起来类似于上面代码列表中的样子:
pokemonList = [
{name: 'Bulbasur',type: ['water']}
];
for (let i=0; i < pokemonList.length; i++) {
console.log(JSON.stringify(pokemonList[i]));
};
您可以对数组中的每个项目使用 JSON.stringifay:
pokemonList.forEach(item => console.log(JSON.stringify(item)));