对象[foo]术语是什么意思? [英] What does the object[foo] term mean?

查看:162
本文介绍了对象[foo]术语是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑对象[foo] 术语所指的是什么。任何提示?我知道 bar ['unique_prop'] bar.unique_prop 指的是 2

I'm confused what the object[foo] term is referring to. Any hints? I know that bar['unique_prop'] and bar.unique_prop refers to 2

    var foo = {unique_prop: 1};
    var bar = {unique_prop: 2};
    var object = {};
    object[foo] = 'value';
    alert(object[bar]);

jsfiddle上的代码

推荐答案

这:

var foo = 'abc';
object[foo]

相当于:

object.abc

但是这样:

var foo = {unique_prop: 1};
object[foo] = 'value';

没有多大意义(对象属性名称不能是对象文字)。 JS引擎将使用 foo.toString()(返回例如[object Object]),所以实际上你正在这样做:

Doesn't have much sense (object property names cannot be object literals). JS engine will use foo.toString() (returning e.g. "[object Object]"), so in fact you are doing this:

var foo = {unique_prop: 1};
object["[object Object]"] = 'value';

这显然是一个错误或误解。 会员运营商中解释了此行为: //developer.mozilla.org/en/JavaScript\"rel =nofollow> MDN :

which is clearly a bug or a misunderstanding. This behaviour is explained in Member Operators on MDN:


属性名称必须是字符串。这意味着非字符串对象不能用作对象中的键。任何非字符串对象(包括数字)都通过toString方法进行类型转换为字符串。

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

但是你可以使用:

object[foo.unique_prop] = 'value';

相当于:

object[1] = 'value';

这篇关于对象[foo]术语是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆