Property names with spaces in object literals

我与影子孤独终老i 提交于 2020-01-15 23:48:06

问题


I'm just wondering, with the "one", "two", "three" stuff, could there be a space? So instead of "one" it could be "one meow"?

var meow    = { one:        function (t) { return "a"; },
                two:        function (t) { return "b"; },
                three:      function (t) { return "c"; }
              };

回答1:


Sure, there can be spaces in property names, but then you have to enclose them in ":

var meow    = {
            "one meow": function (t) { return "a"; },
            two:        function (t) { return "b"; },
            three:      function (t) { return "c"; }
            };

When you want to access that property later, use the bracket syntax:

console.log( meow["one meow"]() );



回答2:


Yes, but you can no longer access the property as meow.one mewo, instead you need to use the bracket syntax: meow['one mewo'].

Similarly, when you define the object, you need to quote the keys:

var meow = {
  'one meow'  : function (t) { return "a"; },
  two         : function (t) { return "b"; },
  'three meow': function (t) { return "c"; }
};       


来源:https://stackoverflow.com/questions/21724158/property-names-with-spaces-in-object-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!