推荐解决方案
我的建议是添加一个index
密钥
let data = { "names": [ {"name":"John"},
{"name":"Mary"} ] };
// Add an index manually
data = {
names: [
{ id: 0, name: "John" },
{ id: 1, name: "Mary" }
]
};
// Add an index with a loop
data = data.names
.map(function (name, i) {
name.id = i;
return name;
});
// Nested arrays with indices (parentId, childId)
data = {
names: [{
parentId: 0,
name: "John",
friends: [{
childId: 0,
name: "Mary"
}]
}]
};
其他提议的解决方案并不那么干净,并且存在很多问题,如下所述。
建议的 Mustache Index 解决方案的问题
@指数
小胡子不支持@Index
指数
此解决方案在 O(n^2) 时间内运行,因此它没有最佳性能。此外,必须为每个列表手动创建索引。
const data = {
list: ['a', 'b', 'c'],
listIndex: function () {
return data.list.indexOf(this);
}
};
Mustache.render('{{#list}}{{listIndex}}{{/list}}', data);
全局变量
这个解决方案在 O(n) 时间内运行,所以这里的性能更好,但也“污染了全局空间”(即添加到window
对象的任何属性,在浏览器窗口关闭之前不要被垃圾收集),并且索引必须手动为每个列表创建。
const data = {
list: ['a', 'b', 'c'],
listIndex: function () {
return (++window.listIndex || (window.listIndex = 0));
}
};
Mustache.render('{{#list}}{{listIndex}}{{/list}}', data);
局部变量
该解决方案在 O(n) 时间内运行,不会“污染全局空间”,也不需要为每个列表手动创建。但是,该解决方案很复杂,并且不适用于嵌套列表。
const data = {
listA: ['a', 'b', 'c'],
index: () => name => (++data[`${name}Index`] || (data[`${name}Index`] = 0))
};
Mustache.render('{{#listA}}{{#index}}listA{{/index}}{{/listA}}', data);