In Knockout JS, is it possible to do a foreach that increments by 2? Something similar to:
for (var i = 0; i < array.length; i += 2) {
// Do stuff
}
The reason I’d like to do this is because the data that I need to loop through is an array rather than an object. Example:
viewModel = function () {
this.facets = ["Sample", 100, "Sample 2", 200];
}
But the data needs to be displayed like this:
<ul data-bind="foreach: facets"> <!-- Can this foreach be incremented by 2? -->
<li>$data[$index]: $data[$index + 1]</li>
</ul>
Any help would be greatly appreciated.
You could write a custom binding handler for this but I would rather keep the templates free from such ugly details.
I would recommend writing a
ko.computed:Now you can iterate over the
itemsin your template and accesskeyandvalue. Updating the originaldataarray will automatically rebuild theitemscomputed observable.The template code would look like: