我有这样的对象数组:
var students = [
{
name : "Mike",
track: "track-a",
points : 40,
},
{
name : "james",
track: "track-a",
points : 61,
},
]
students.forEach(myFunction);
function myFunction (item, index) {
for( var key in item ) {
console.log(item[key])
}
}
我想像这样在div内输出字符串。 如果点数> 50,则我打印通过;否则,我打印失败,则名称和轨迹如下:
Failed: Mike in track track-a
Passed: james in track track-1
如何构建这样的模板字符串?
答案 0 :(得分:1)
var students = [
{
name : "Mike",
track: "track-a",
points : 40,
},
{
name : "james",
track: "track-a",
points : 61,
},
]
students.forEach((student) => {
console.log(`${student.points > 50 ? 'Passed' : 'Failed'}: ${student.name} in track ${student.track}`);
});
答案 1 :(得分:1)
可以通过映射数组来实现,您不需要额外的功能,请参见下文
var students = [
{
name : "Mike",
track: "track-a",
points : 40,
},
{
name : "james",
track: "track-a",
points : 61,
},
]
const myString = students.map(student => student.points > 50 ? `Passed: ${student.name} in track ${student.track}` : `Failed: ${student.name} in track ${student.track}`);
console.log(myString)
答案 2 :(得分:0)
var a = "Hello";
var b = "World";
var template_string = `${a} ${b}!`; // Backticks here!
console.log( template_string )