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];