Home > Enterprise >  Array.prototype.every on String object
Array.prototype.every on String object

Time:09-06

As we all know this is a valid code, which will return false because test_string contains an s:

Array.prototype.every.call('test_string', n => n === 's')

My question is: can I implement my object (a generator for example) which I will be able to pass to Array.prototype.every.call so it runs predicates on my my objects items. Thank you.

CodePudding user response:

Yes, an object is fine (but a generator not so much) - it's not very picky so long as the thing you pass has length.

After all, the spec is clear that an ArrayLike object is enough.

> a = {length: 3}
> a[0] = 1
> a[1] = 2
> a[2] = 3
> Array.prototype.every.call(a, p => p < 1)
false
> Array.prototype.every.call(a, p => p <= 3)
true

Furthermore, if you need to, you can pass in a Proxy for an anonymous object that returns your desired length and values for each index from 0 up to length:

> const o = new Proxy(
  {},
  {
    get(target, prop, receiver) {
      if (prop === "length") return 8;
      const idx =  prop;
      if (!isNaN(idx)) {
        return idx ** 3;
      }
    },
  },
);
> o.length
8
> o[4]
64

and as that's an ArrayLike object, it should work with all Array methods.

CodePudding user response:

What .every does is:

2. Let len be ? LengthOfArrayLike(O).
3. If IsCallable(callbackfn) is false, throw a TypeError exception.
4. Let k be 0.
5. Repeat, while k < len,
  a. Let Pk be ! ToString(           
  • Related