Closed Bug 956256 Opened 10 years ago Closed 10 years ago

Access to Map elements using [ ] and for ... in operators

Categories

(Core :: JavaScript Engine, defect)

defect
Not set
normal

Tracking

()

RESOLVED INVALID

People

(Reporter: kolan_n, Unassigned)

References

Details

User Agent: Mozilla/5.0 (Windows NT 6.2; rv:26.0) Gecko/20100101 Firefox/26.0 (Beta/Release)
Build ID: 20131205075310

Steps to reproduce:

let a=new Map();
a["x"]="y";
a["z"]="w";
console.log(a.has("z"));
console.log(a.get("x"));
console.log("--------------");
let a=new Map();
a.set("x","y");
a.set("z","w");
for(let b in a){
    console.log(b);
}


Actual results:

false
undefined
--------------
undefined


Expected results:

true
y
--------------
x
z
OS: Windows 8 → All
Hardware: x86 → All
This is working as intended. One of the reasons Map and Set don't use the normal object property access mechanisms is that those coerce all keys to strings. Maps and Sets allow you to use objects as keys, with the object identity being used, not their string value. Changing the behavior of object properties would break pretty much all code in existence, so Map and Set need to use a different interface.

As a demonstration of the difference, the following code:

var x = {toString: function() {return "x";}};
var otherX = {toString: function() {return "x";}};
var obj = {};
obj[x] = 'x value';
console.log("object values:");
console.log(obj['x']); // prints 'x value'
console.log(obj[otherX]); // prints 'x value'

var map = new Map();
map.set(x, 'x value');
map.set('x', 'literal x value');
map.set(otherX, 'otherX value');
console.log("map entries:");
for (value of map) // prints three different entries
    console.log(value);
Status: UNCONFIRMED → RESOLVED
Closed: 10 years ago
Resolution: --- → INVALID
Maybe we should introduce a new operator to access without cast to string, for example [[ ]]
Status: RESOLVED → UNCONFIRMED
Resolution: INVALID → ---
You can suggest that on <https://mail.mozilla.org/listinfo/es-discuss>.
Status: UNCONFIRMED → RESOLVED
Closed: 10 years ago10 years ago
Resolution: --- → INVALID
Such an operator has been discussed on es-discuss. A quick search yields this thread: https://mail.mozilla.org/pipermail/es-discuss/2011-October/thread.html#17468

In general, this bugtracker is only about our implementation of the language, not about changes to the language's specification.
thanks, will read
(In reply to KOLANICH from comment #2)
> Maybe we should introduce a new operator to access without cast to string,
> for example [[ ]]

This particular syntax is actually valid syntax in since ES3: 

var a = [[1]]; 
a[[0]]; // this will be coerced to a string "0"
// [1]

Because: 

MemberExpression [ Expression ]
< > ?
You need to log in before you can comment on or make changes to this bug.