javascript JSON 和 Array 元素,帮助我理解有关引号的规则
当使用返回值来确定数组中元素的数量时,javascript 是否会在其周围添加引号?
示例:
这会统计使用唯一字符的次数。
var uniques = {};
function charFreq(s)
{
for(var i = 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"));
看起来很有趣的是 uniques[s.charAt(i)] 有效,而 uniques[a] 不起作用(由于缺少引号)。 uniques[a] 会给你一个令人讨厌的“a 未定义”。
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 = 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'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您使用
[]
表示法访问JavaScript对象时,您正在使用字符串作为对象中的键。您还可以使用.
表示法来寻址属性:uniques.a 与
uniques['a']
相同。向
s.charAt(i)
添加引号是因为它返回一个字符串,然后将其用作属性来检查uniques
目的。uniques[a]
将产生错误,因为尚未定义名为a
的变量。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 asuniques['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 theuniques
object.uniques[a]
will create an error, because no variable with the namea
has been defined.在第一个版本中 -
uniques[s.charAt(i)]
- 您使用表达式进行查找。 JavaScript 计算表达式 -s.charAt(i)
- 并使用计算出的值(可能是a
)在uniques
中执行查找> 地图。在第二个版本中 -
uniques[a]
- 您希望使用 literal 字符a
进行查找,但除非您将其包装起来在引号中,JavaScript 将a
视为表达式而不是文字。当它尝试计算“表达式”时,您会收到错误。所以规则是:字符/字符串文字需要引号;计算结果为字符/字符串的表达式则不然。
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 (maybea
) to perform the lookup in theuniques
map.In the second version --
uniques[a]
-- you want to do the lookup using the literal charactera
, but unless you wrap it in quotes then JavaScript treats thea
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.
这就是 Javascript 如何计算 [] 之间的表达式,如
uniques[s.charAt(i)]
,其类型为 MemberExpression[ Expression ] :因此,在第三步中,它将属性名称转换为字符串。
This is how Javascript evaluates the expression between [] like
uniques[s.charAt(i)]
which is of the type MemberExpression[ Expression ] :So in the 3rd step it is converting the property name into a string.