for statement with index and value
Sebastian Zartner
sebastianzartner at gmail.com
Wed Jul 15 06:21:29 UTC 2015
That only works if all values are distinct. The following will result
in the wrong index for the last item:
let values = ["a", "b", "a"];
for (let value of values) {
let index = values.indexOf(value);
}
Also that construct is not very performant.
Sebastian
On 15 July 2015 at 03:02, Rick Waldron <waldron.rick at gmail.com> wrote:
> If you need the _index of_ a value in an array, there is always... "indexOf"
> ;)
>
> for (let value of values) {
> let index = values.indexOf(value);
> }
>
> Rick
>
> On Tue, Jul 14, 2015 at 4:16 PM Tab Atkins Jr. <jackalmage at gmail.com> wrote:
>>
>> On Mon, Jul 13, 2015 at 7:13 PM, Tingan Ho <tingan87 at gmail.com> wrote:
>> > Just following a discussion we had on TypeScript
>> > https://github.com/Microsoft/TypeScript/issues/3835
>> >
>> > In most times, I just need the value in an array, so I use a for..of
>> > loop.
>> > But then, I find out that I need the index too, then I need to rewrite
>> > my
>> > whole for loop expression. Happens all the time for me.
>> >
>> > I have to ask why there doesn't exist a `for statement` where I can get
>> > the
>> > index and value of an array directly? Or for that matter property and
>> > value
>> > of an object?
>> >
>> > `.forEach` is not ideal since you can't break, break to outer loop and
>> > continue cleanly. Even though you can achieve this with other array
>> > methods,
>> > I don't think they are as productive as a for-statement.
>> >
>> > What I'm suggesting is augmenting the current syntax for `for..of`
>> > loops.
>> > And support an overloading pattern so that we don't need to rewrite the
>> > whole for loop expression to just to get the index when we already
>> > getting
>> > the value.
>> >
>> > ```
>> > // overloads
>> > for (let value, index of values) { ... }
>> > for (let value of values) { ... }
>> > ```
>> >
>> > PS. Sorry if this has already discussed. Couldn't find any on Google and
>> > the
>> > esdiscuss.org page doesn't have any search capabilities.
>>
>> Kevin provided the built-in answer for arrays, but for arbitrary
>> iterables, the Python solution is trivial:
>>
>> function* enumerate(iter) {
>> let i = 0;
>> for(let value of iter) {
>> yield [i, value];
>> i++
>> }
>> }
>>
>> for(let [i, v] of enumerate(values)) {
>> ...
>> }
>>
>> I expect there's already libraries that duplicate all of Python's
>> itertools and more; the iterator algebra is really trivially hackable.
>>
>> ~TJ
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
More information about the es-discuss
mailing list