Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - 如何动态创建JavaScript对象?(How to create javascript objects dynamically?)

Is it possible to set javascript objects dynamically?(是否可以动态设置javascript对象?)

I your create objects this way:(我以这种方式创建对象:) let data = {a: {b: 'value'}}; but I need to create it this way:(但是我需要这样创建它:) let data ['a'] ['b'] = 'value'; Object creation will happen within a loop dynamically.(对象创建将在循环内动态发生。) That's why I need the second way.(这就是为什么我需要第二种方式。)   ask by Jobsdev translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't in Javascript, because [] operator cannot override in JavaScript.(您无法使用Javascript,因为[]运算符无法在JavaScript中覆盖。)

If you use ruby, you can by following way.(如果使用红宝石,则可以通过以下方式进行。) class MyHash < Hash def [](key) if has_key? key super else self[key] = self.class.new end end end my_hash = MyHash.new my_hash[1][2][3] = "a" puts my_hash => {1=>{2=>{3=>"a"}}} This can be done by "[]" operator overriding.(这可以通过“ []”运算符覆盖来完成。) JavaScript doesn't support "[]" operator overriding.(JavaScript不支持“ []”运算符覆盖。) How would you overload the [] operator in javascript(您如何在javascript中重载[]运算符) Then you should(那你应该) lat data = {} data[a] = data[a] ? data[a] : {} data[a][b] = "value"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...