What is special about an argument named keys in javascript?
I'm seeing bizarre behavior when I name the argument for a function keys
. In the first function (set), I name it keeys, and it works as expected, in the second function (xset) I call it keys and it makes no sense. I've looked @ the rese开发者_开发知识库rved words for javascript and no one mentions keys or set as keywords, however Chromium script console (and SO) colors set (but not keys) as if it is a keyword like var, return, for, true...
Anyway, here is the code:
<html>
<body>
<script type='text/javascript'>
function set (keeys) {
var result = {};
for (var i = 0; i < keeys.length; i++)
result[keeys[i]] = true;
return result;
}
function xset (keys) {
var result = {};
for (var i = 0; i < keys.length; i++)
result[keys[i]] = true;
return result;
}
var myset1 = set(['a','b','c','d','e']);
var myset2 = xset(['a','b','c','d','e']);
</script>
</body>
</html>
And here is the debugger output from Chromium. Breakpoint @ first line of set:
> keeys
> ["a", "b", "c", "d", "e"]
> keeys.length
> 5
Break point @ first line of xset:
> keys
> function (object)
{
return Object.keys(object);
}
> keys.length
> 1
It's most likely a bug, since the following works correctly for me (Chrome 11.0.696.60):
function bloop(keys) {
console.log(keys);
}
And, after writing this test, ran your code in the console and then in jsbin (open your console.) Works flawlessly. If you wish, report it as a bug to the Chromium project.
A possible way of tip-toeing around the problem, if you don't want to use keys
, is to run this at the top of the script:
if (keys !== undefined)
var keys = undefined;
And then you can resume normally.
Edit: For those confused, there's a new function added in ES5 (shiny sparkly JavaScript) to the Object
variable called keys
. It's called like this:
Object.keys({suzy : 4, companion : 'cube', turtle : 'orange'});
//returns ["suzy", "companion", "turtle"]
//or, more abstractly
Object.keys(obj);
It returns an array of all the keys in obj
. Note that keys
resides in Object
, NOT Object.prototype
, so there is no "hi".keys()
or obj.keys()
.
Now, for development purposes, the Chromuim team introduced some console-specific functions (like clear
), which can only be called via the console, and not anywhere else. One of them is a shortcut to Object.keys
, called keys
.
Due to perhaps a bug these functions leaked out, causing the problem.
I'm not exactly positive, but my best guess is that it has something to do with Object.keys, introduced to Javascript in version 1.8.5.
Note, also, that javascript arrays are really just javascript objects which is going to further compound the issue.
Very curious, on Chromium 13.0.751.0 I see the following
> keys
bound: function (object)
{
return Object.keys(object);
}
> window.keys
undefined
> (1).keys
undefined
> "asd".keys
undefined
> {}.keys
SyntaxError: Unexpected token .
> [].keys ()
TypeError: Object has no method 'keys'
Can anyone make any sense out of this?
精彩评论