简体   繁体   English

关于文字对象语法的限制

[英]About the limitation of the literal object syntax

I know that the limitation of the literal object syntax is that the names has to be literal. 我知道文字对象语法的限制是名称必须是文字的。

By the way I need to accomplish the following task, which way do you recommend me? 顺便说一下,我需要完成以下任务,你推荐我哪种方式?

I have an object obj1 which I want traverse and then pass to another function which accept only literal object like parameter. 我有一个对象obj1,我想遍历,然后传递给另一个只接受像参数这样的文字对象的函数。

I wrote just the basic example to get the basic idea of what I am asking. 我只写了一个基本的例子,以了解我所要求的基本概念。

The problem is on the last loop, see the inline comments. 问题出在最后一个循环中,请参阅内联注释。

obj1 = {k1 : 1} // simple literal object

fn = function (json) {
    // this function can accept just  literal object 
    console.log("result: ", json); // {key : true}, but I want {k1 : true}
}

for (key in obj1) {
    obj = [];
    fn ({
        key : true // I want the key to be k1 and not key
    })
};

Just do this... 这样做......

var obj = {};
obj[key] = true;
fn(obj);

That is about as elegant as you will get. 那就像你会得到的那样优雅。 Please do not use eval() . 请不要使用eval()

Use bracket notation to use a variable as a key. 使用括号表示法将变量用作键。

function fn(obj) {
    console.log("result: ", obj);
}

for (var key in obj1) {
    var temp = {};
    temp[key] = true;
    fn (temp);
};

Also note the use of var (so you don't create globally-scope variables) and the different style function declaration. 另请注意var的使用(因此您不创建全局范围变量)和不同的样式函数声明。

 // this function can accept just  literal object 

No. The function does not care how the parameter object was constructed. 不。该功能不关心参数对象的构造方式。

You can do 你可以做

 obj = {};
 key = "k1";
 obj[key] = true;
 fn(obj);

another function which accept only literal object like parameter. 另一个只接受像参数这样的文字对象的函数。

There's no such thing. 没有这样的事情。 Outside of the moment it is created, there is no difference between an object created using a literal and one created some other way. 在创建它的那一刻之外,使用文字创建的对象和使用其他方式创建的对象之间没有区别。

for (key in obj1) {
    obj = [];
    var foo = {};
    foo[key] = true;
    fn (foo);
};

May be try this? 可以尝试一下吗?

for (key in obj1) {
  var obj = {};
  obj[key] = true;
  fn (obj);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM