javascript JSON and Array elements, help me understand the rule about quotes
When using a returned value to determine the number of an element in an array, does javascript throw quotes around it?
Example :
This tallys the number of times unique characters are used.
var uniques = {};
function charFreq(s)
{
for(var i = 开发者_Python百科0; i < s.length; i++)
{
if(isNaN(uniques[s.charAt(i)])) uniques[s.charAt(i)] = 1;
else uniques[s.charAt(i)] = uniques[s.charAt(i)] + 1;
}
return uniques;
}
console.log(charFreq("ahasdsadhaeytyeyeyehahahdahsdhadhahhhhhhhhhha"));
It just seems funny that uniques[s.charAt(i)] works, and uniques[a] wont work (due to lack of quotes). uniques[a] will get you a nasty 'a is undefined'.
When you access a JavaScript object using the []
notation, you are using a string as a key in the object. You can also address properties using the .
notation:
uniques.a
is the same as uniques['a']
The reason you aren't adding quotes to the s.charAt(i)
is that it returns a string, which is then used as the property to check on the uniques
object.
uniques[a]
will create an error, because no variable with the name a
has been defined.
In the first version -- uniques[s.charAt(i)]
-- you're doing the lookup using an expression. JavaScript evaluates the expression -- s.charAt(i)
-- and uses the evaluated value (maybe a
) to perform the lookup in the uniques
map.
In the second version -- uniques[a]
-- you want to do the lookup using the literal character a
, but unless you wrap it in quotes then JavaScript treats the a
as an expression rather than a literal. When it tries to evaluate the "expression" then you get an error.
So the rule is: character/string literals need quotes; expressions that evaluate to characters/strings don't.
This is how Javascript evaluates the expression between [] like uniques[s.charAt(i)]
which is of the type MemberExpression[ Expression ] :
- Let propertyNameReference be the result of evaluating Expression.
- Let propertyNameValue be GetValue(propertyNameReference).
- Let propertyNameString be ToString(propertyNameValue).
So in the 3rd step it is converting the property name into a string.
精彩评论