Javascript-Handlebars helper比较两个数组并返回差值
作者:互联网
我是handlebars.js的新手,我需要一个handlebars助手来比较两个数组并返回差值.
我已经尝试过该示例,但它对我不起作用.我想我在犯一些错误.
请在下面找到我的代码并纠正我.
Java脚本
var subscriptionInfo = {
subscription : "oldFeature",
feature : {
oldFeature : ["1 Free Projects", "10 MB Storage Space", "Project Feeds","Task Management"],
newFeature : ["10 Free Projects", "1 GB Storage Space", "Project Feeds","Task Management"]
}
模板
<ul class='featureList'>
{{#feature}}
{{#oldFeature}}
<li class="{{arraysDiff ../oldFeatur ../newFeature}} myclass {{arraysDiff}}">{{.}}</li>
{{/oldFeature}}
{{/feature}}
</ul>
解决方法:
您需要做的第一件事是一种计算两个数组差异的方法.根据要比较的数组类型,您可能需要其他方法才能获得具有差异的数组.在此示例中,我将使用this other SO answer中说明的方法.
function arr_diff(a1, a2)
{
var a=[], diff=[];
for(var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for(var i = 0; i < a2.length; i++) {
if (a[a2[i]])
delete a[a2[i]];
else
a[a2[i]] = true;
}
for(var k in a) {
diff.push(k);
}
return diff;
}
然后,您可以注册您的Handlebars助手来使用上述方法,如下所示:
Handlebars.registerHelper('arraysDiff', function(arrayA, arrayB, opts)
{
var result = arr_diff(arrayA, arrayB);
return opts.fn(result);
});
最后,您可以在Handlebars模板中使用此帮助程序:
{{#arraysDiff this.jsonArray1 this.jsonArray2}}
<!-- Do something with the difference array, e.g. print it -->
{{this}}
{{/arraysDiff}}
标签:handlebars-js,html,javascript 来源: https://codeday.me/bug/20191122/2057761.html