关于文字对象语法的限制

About the limitation of the literal object syntax

本文关键字:语法 对象 于文字 文字      更新时间:2023-09-26

我知道literal对象语法的局限性在于名称必须是literal。

顺便说一下,我需要完成以下任务,你推荐我用哪种方式?

我有一个对象obj1,我想遍历它,然后将它传递给另一个函数,该函数只接受类似文字对象的参数。

我只写了一个基本的例子来了解我所要求的基本内容。

问题出现在最后一个循环中,请参阅内联注释。

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
    })
};

只需执行此操作。。。

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

这几乎是你将得到的优雅。请不要使用eval()

使用括号表示法将变量用作键。

function fn(obj) {
    console.log("result: ", obj);
}
for (var key in obj1) {
    var temp = {};
    temp[key] = true;
    fn (temp);
};

还要注意var的使用(这样就不会创建全局范围变量(和不同风格的函数声明。

 // this function can accept just  literal object 

没有。函数不关心参数对象是如何构造的。

你可以做

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

另一个只接受类似文字对象的参数的函数。

没有这样的事情。除了创建的那一刻,使用文字创建的对象和以其他方式创建的对象之间没有区别。

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

可以试试这个吗?

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