javascript - 如果长度未知, Handlebars 返回具有特定索引的数组元素

标签 javascript arrays node.js handlebars.js express-handlebars

使用 Handlebars 和 Node,我有一个长度不断变化的数组,每次它发生变化时我都需要获取最后一个元素之前的元素。

所以如果你想得到最后一个元素,你可以这样做:

{{#each array}}
  {{#if @last}}
    {{this}}
  {{/if}}
{{/each}}

它会返回最后一个元素。 我有数学助手,可以执行基本的数学运算。 例如,我可以获得所需的索引号

{{math array.length '-' 1}}

但我不能将它与另一个 block 助手一起使用,例如:

{{#each array}}
  {{#if math @last '-' 1}}
    {{this}}
  {{/if}}
{{/each}}

这怎么可能?谢谢。

最佳答案

您可以为此注册自己的助手:

Handlebars.registerHelper('isSecondLastArrayItem', function(array, index, options) {

  if((array.length - 2) === index)
    return options.fn(this);

  return;

});

然后像这样使用它:

{{#each array}}
  {{#isSecondLastArrayItem @root.array @index}}
    {{title}}
  {{/isSecondLastArrayItem}}
{{/each}}

示例数据:

{ 
  array: [{ title: 'aa' }, { title: 'vv' }]
}

sandbox 中试用.

编辑:任何索引的大小写

Handlebars.registerHelper('isNthLastArrayItem', function(array, index, offset, options) {

  if(((array.length >= offset) && (array.length - offset) === index)
    return options.fn(this);

  return;

});

用法(对于末尾的 2nd 项):

{{#each array}}
  {{#isNthLastArrayItem @root.array @index 2}}
    {{title}}
  {{/isNthLastArrayItem}}
{{/each}}

关于javascript - 如果长度未知, Handlebars 返回具有特定索引的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46897761/

相关文章:

Python:折线周围的坐标框

java - 由于相同的 HaschCode(重复对象),ArrayList 对象值更改

node.js - 不小心删除了nodejs.log,现在Openshift不记录任何内容。

node.js - Mongoose ,从数组中删除一个对象并更新其他对象

javascript - NodeJS - 对象的对象未定义?

javascript - Node.js HTTP 请求返回 2 个 block (数据体)

javascript - 使用 React 动态隐藏内容

javascript - react 谷歌地图未捕获类型错误 : Cannot read property 'overlayMouseTarget' of null

javascript - 在 jQuery Deferred/Promise 中包装 webSql executeSql 调用

python - 计算每行在 numpy.array 中出现的次数