Search code examples
javascriptecmascript-6es6-proxy

Proxy index gets converted to string


Trying out the new Proxy objects, I am surprised that when a proxy is set the key is automatically converted to a string:

var arr = ['a', 'b', 'c'];

arr = new Proxy(arr, {
  get: (original, key) => {
    alert(typeof key);
    return original[key];
  }
});

arr[1];  // expected an alert with 'number'; got 'string' instead

There I would expect that typeof key would be number, since I am passing it a number. However, it gets converted to a string inside Proxy somehow and the actual alerted type is string. You can see a small JSFiddle here that showcases the problem. arr is still an Array even after passing it through the proxy.

So, how could I differentiate from passing a string and a number? I could just regex it out as in /\d+/.test(key), however it'd not differentiate between these situations and it just feels like a hack:

arr['1'];
arr[1];

Solution

  • Property keys can be only strings or symbols. If you're using something different, like a number, it always gets converted to a string first. Therefore, when using a Proxy you can't distinguish between these two operations:

    arr['1'];
    arr[1];
    

    Both of them will trigger the Proxy get handler with '1' as the property key.


    Also, the fact that you're using an array doesn't change anything―it works the same with arrays (which are special kind of objects) as it works with plain objects.


    See also The Object Type in the specification.