[英]How can I insert a string to the first iteration of a loop only?
Okay so I have this array of objects which are dynamic.好的,所以我有这个动态对象数组。 It can have
100
objects inside or only one
.它里面可以有
100
对象,也可以只有one
。 I have been rendering html from server side by iterating through the array.我一直在通过遍历数组从服务器端呈现 html。 That part works fine but what I want to do is I want to insert a piece of
string
to the first iteration
only.这部分工作正常,但我想要做的是我只想在
first iteration
插入一段string
。 Which means I want the value of power to be in the first iteration, which is Steve Rogers
and I want the value of power to be in the first td
just before the anchor tag.这意味着我希望 power 值出现在第一次迭代中,也就是
Steve Rogers
,我希望 power 值出现在锚标签之前的第一个td
。
Please note again that arr
can have any amount of objects.请再次注意,
arr
可以有任意数量的对象。
Here's the code:这是代码:
const arr = [
{
"name": 'Steve Rogers',
"age": 90,
"bio": 'https://www.boomboom.com'
},
{
"name": 'Natasha Romanoff',
"age": 30,
"bio": 'https://www.bambam.com'
}
];
const power = 'Super-Strength <br><br>';
const arrMap = arr.map(el => {
return `
<td>
<a href="${el.bio}">Bio</a>
</td>
<td>${el.name}</td>
<td>${el.age}</td>
`;
});
Expected result is an array of two chunk of strings:预期结果是两个字符串块的数组:
[
'<td>
Power: Super-Strength <br><br>
<a href="https://www.boomboom.com">Bio</a>
</td>
<td>Steve Rogers</td>
<td>90</td>',
'<td><a href="https://www.bambam.com">Bio</a></td>
<td>Natasha Romanoff</td>
<td>30</td>'
]
Here you go:干得好:
var arr = [ { "name": 'Steve Rogers', "age": 90, "bio": 'https://www.boomboom.com' }, { "name": 'Natasha Romanoff', "age": 30, "bio": 'https://www.bambam.com' } ]; var power = 'Super-Strength <br><br>'; var arrMap = arr.map((el,i) => { return `<td>${i==0 ? "Power: "+power : ""}<a href="${el.bio}">Bio</a></td><td>${el.name}</td><td>${el.age}</td>`; }); console.log(arrMap)
You just need pass index parameter to Array.prototype.map as follows:您只需要将 index 参数传递给 Array.prototype.map 如下:
const arr = [ { "name": 'Steve Rogers', "age": 90, "bio": 'https://www.boomboom.com' }, { "name": 'Natasha Romanoff', "age": 30, "bio": 'https://www.bambam.com' } ]; const power = 'Super-Strength <br><br>'; const arrMap = arr.map((el, index) => { return ` <td> ${index === 0 ? "Power: " + power : ""}<a href="${el.bio}">Bio</a> </td> <td>${el.name}</td> <td>${el.age}</td> `; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.