I was attempting to iterate over something n times but couldn't do it the easy way.
<template x-for="index in 4"></template>
Here's a pen: https://codepen.io/KevinBatdorf/pen/NWGOaqo
Also, this doesn't appear to work either (but does in vue):
<template x-for="index in new Array(4)"></template>
This works:
<template x-for="index in Array.from(Array(4).keys())">
x-for only works with arrays, not integers, and it also needs defined elements: one of your examples, Array(4), creates an array with length = 4 but 0 elements in it (more details here if you are interested in the technical details -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length).
It's not obvious but the doc says 'x-for is available for cases when you want to create new DOM nodes for each item in an array.'
There was a PR to support objects but it got declined for now so I'm not sure if the author would like to support integers at the moment.
Your last attempt is the closest thing you can do to match the Vue example.
Couple of other ways to do this:
x-for="index in Array.from({ length: 4 })"x-for="index in Array(4).fill(null)"~Although none of this really has anything to do with Alpine.js we're answering the question: "how to generate an array of length n in JavaScript"~ correction Alpine.js skips handling empty elements
I think Array.from({ length: 4 }) reads nicely enough. Thanks.
Anyway, I was just porting something simple over from vue and noticed the difference. Not sure whether it's trivial to implement it or not.
Although I don't think adding support for Array(4) would be too difficult (it would probably entail swapping forEach for a for loop in the x-for directive implementation) I wouldn't be too keen to add it since there's a userland workaround.
Feel free to submit a PR though.
Personally I think it's fine without it. Having this issue exist along with all the examples above is likely enough to help someone else who runs into this situation and isn't sure what to do.
Feel free to close the issue at your discretion. Thanks!
Cool thanks for your feedback.
If anybody gets stumped by this in future, feel free to reopen