Javascript 如何在aurelia阵列中继器上反向迭代?
我试图从数组的末尾迭代到数组的开头 例如: repeater-template.js:Javascript 如何在aurelia阵列中继器上反向迭代?,javascript,arrays,aurelia,Javascript,Arrays,Aurelia,我试图从数组的末尾迭代到数组的开头 例如: repeater-template.js: export class RepeaterTemplate { constructor() { this.friends = [ 'Alice', 'Bob', 'Carol', 'Dana' ]; } } repeater-template.html: <template> <p repeat.for.reverse ="friend of friends"
export class RepeaterTemplate {
constructor() {
this.friends = [
'Alice',
'Bob',
'Carol',
'Dana'
];
}
}
repeater-template.html:
<template>
<p repeat.for.reverse ="friend of friends">Hello, ${friend}!</p>
</template>
据我所知,Aurelia对此没有任何明确的函数,但您可以在viewmodel中创建一个简单的函数:
reverse(arr) {
return arr.slice().reverse();
}
然后在视图中:
<template>
<p repeat.for="friend of reverse(friends)">Hello, ${friend}!</p>
</template>
您好,${friend}
或你好,${friend}
如果数组发生变异,我认为公认的解决方案不起作用。我认为理想的方法是创建一个值转换器,它返回反向数组而不改变原始数组。例如:
JS
HTML
你好,${friend}
运行示例:
我们无法在此处使用computed属性,因为
@computedFrom
尚不支持集合
另一种可能的解决方案是通过BindingEngine订阅该数组,并在其发生变化时更新反向副本,但这将需要太多的代码来解决一个简单的问题
希望这有帮助 @Fabioloz-我的回答是一条捷径。完整代码是添加例如
this.friends=Array.prototype.reverse.call(this.friends)在构造函数中单击code>,然后单击您好,${friends}
asrepeat.for
希望列表是类属性。。谢谢-我应该回答得更准确些。你能解释一下为什么需要调用slice()
吗?需要slice()
来“复制”数组。否则,实际数组将发生变异。
<template>
<p repeat.for="friend of reverse(friends)">Hello, ${friend}!</p>
</template>
export class App {
message = 'Hello World!';
friends = ['a', 'b', 'c'];
attached() {
//MUTATE!
setTimeout(() => { this.friends.push('d') }, 300);
}
}
export class ReverseValueConverter {
toView(array) {
return array.slice().reverse();
}
}
<p repeat.for="friend of friends | reverse">Hello, ${friend}!</p>