Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何为JavaScript对象文本中的键使用变量?_Javascript_Jquery_Variables_Properties_Object Literal - Fatal编程技术网

如何为JavaScript对象文本中的键使用变量?

如何为JavaScript对象文本中的键使用变量?,javascript,jquery,variables,properties,object-literal,Javascript,Jquery,Variables,Properties,Object Literal,为什么下面的工作 <something>.stop().animate( { 'top' : 10 }, 10 ); .stop().animate( {'top':10},10 ); 但这不起作用: var thetop = 'top'; <something>.stop().animate( { thetop : 10 }, 10 ); var thetop='top'; .stop().animate( {thetop:10},10 ); 更

为什么下面的工作

<something>.stop().animate(
    { 'top' : 10 }, 10
);
.stop().animate(
{'top':10},10
);
但这不起作用:

var thetop = 'top';
<something>.stop().animate(
    { thetop : 10 }, 10
);
var thetop='top';
.stop().animate(
{thetop:10},10
);

更清楚地说:目前我无法将CSS属性作为变量传递给animate函数。

{thetop:10}
是有效的对象文本。代码将创建一个名为
thetop
的属性值为10的对象。以下两者相同:

obj = { thetop : 10 };
obj = { "thetop" : 10 };
在ES5及更早版本中,不能在对象文本中使用变量作为属性名。您唯一的选择是执行以下操作:

var thetop = "top";

// create the object literal
var aniArgs = {};

// Assign the variable property name with a value of 10
aniArgs[thetop] = 10; 

// Pass the resulting object to the animate method
<something>.stop().animate(
    aniArgs, 10  
);  
var thetop = 'top';
var config = (
  obj = {},
  obj['' + thetop] = 10,
  obj
); // config.top = 10
<something>.stop().animate(config, 10);

您可以在每个主流浏览器的最新版本中使用此新语法。

我使用以下方法将具有“动态”名称的属性添加到对象中:

var key = 'top';
$('#myElement').animate(
   (function(o) { o[key]=10; return o;})({left: 20, width: 100}),
   10
);
是新属性的名称

传递给
animate
的属性对象将是
{left:20,width:100,top:10}


这只是使用了其他答案推荐的所需的
[]
符号,但代码行更少

ES5中的一句话说它不应该起作用

注意:ES6的规则已更改:

规格:

PropertyName:

  • 识别名
  • StringLiteral
  • 数字文字
[……]

生产属性名称:IdentifierName的评估如下:

  • 返回与IdentifierName包含相同字符序列的字符串值
  • 生产属性名称:StringLiteral的计算如下:

  • 返回StringLiteral的SV[String value]
  • 生产属性Name:NumericLiteral的计算如下:

  • 假设nbr是形成NumericLiteral值的结果
  • 返回到管柱(nbr)
  • 这意味着:

    • {theTop:10}
      {'theTop:10}

      PropertyName
      theTop
      是一个
      标识名
      ,因此它被转换为
      'theTop'
      字符串值,即
      'theTop'
      的字符串值

    • 无法使用变量键编写对象初始值设定项(文字)

      仅有的三个选项是
      IdentifierName
      (展开为字符串文字)、
      StringLiteral
      NumericLiteral
      (也展开为字符串)

    现在,您可以在带有括号符号的对象声明中直接执行此操作:

    var obj = {
      [key]: value
    }
    
    其中,
    key
    可以是返回值的任何类型的表达式(例如变量)

    因此,您的代码如下所示:

    <something>.stop().animate({
      [thetop]: 10
    }, 10)
    
    .stop().animate({
    [顶部]:10
    }, 10)
    

    其中
    顶部将在用作键之前进行评估。

    在变量周围添加方括号对我很有好处。试试这个

    var thetop = 'top';
    <something>.stop().animate(
        { [thetop] : 10 }, 10
    );
    
    var thetop='top';
    .stop().animate(
    {[thetop]:10},10
    );
    
    给定代码:

    var thetop = 'top';
    <something>.stop().animate(
        { thetop : 10 }, 10
    );
    
    ES6引入了方括号语法。在早期版本的JavaScript中,您必须执行以下操作:

    var thetop = "top";
    
    // create the object literal
    var aniArgs = {};
    
    // Assign the variable property name with a value of 10
    aniArgs[thetop] = 10; 
    
    // Pass the resulting object to the animate method
    <something>.stop().animate(
        aniArgs, 10  
    );  
    
    var thetop = 'top';
    var config = (
      obj = {},
      obj['' + thetop] = 10,
      obj
    ); // config.top = 10
    <something>.stop().animate(config, 10);
    
    var thetop='top';
    变量配置=(
    obj={},
    obj[''+thetop]=10,
    obj
    ); // config.top=10
    .stop().animate(配置,10);
    
    通过这种方式,您也可以获得所需的输出

    var jsonobj={};
    var计数=0;
    $(文档).on('click','btnadd',函数(){
    jsonobj[count]=新数组({“1”:$(“#txtone”).val()},{“2”:$(“#txtwoo”).val()});
    计数++;
    console.clear();
    console.log(jsonobj);
    });
    
    
    值1
    价值2
    
    添加ES5实现以分配密钥,如下所示:

    var obj = Object.create(null),
        objArgs = (
          (objArgs = {}),
          (objArgs.someKey = {
            value: 'someValue'
          }), objArgs);
    
    Object.defineProperties(obj, objArgs);
    
    我附加了一个用于转换为裸体对象的片段

    var obj={
    “键1”:“值1”,
    “键2”:“值2”,
    “键3”:[
    “价值3”,
    “价值4”,
    ],
    “关键4”:{
    “键5”:“值5”
    }
    }
    var bareObj=功能(obj){
    var objArgs,
    bareObj=Object.create(null);
    Object.entries(obj.forEach)(函数([键,值]){
    变量objArgs=(
    (objArgs={}),
    (objArgs[键]={
    价值:价值
    }),objArgs);
    对象。定义属性(bareObj、objArgs);
    });
    返回{
    输入:obj,
    输出:bareObj
    };
    }(obj);
    如果(!Object.entries){
    Object.entries=函数(obj){
    var-arr=[];
    Object.keys(obj).forEach(函数(key){
    arr.push([key,obj[key]]);
    });
    返回arr;
    }
    }
    
    控制台(bareObj)您可以对ES5执行以下操作:

    var theTop = 'top'
    <something>.stop().animate(
      JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
    )
    
    var theTop='top'
    .stop().animate(
    JSON.parse('{'+theTop+'':'+JSON.stringify(10)+'}'),10
    )
    
    或提取到函数:

    function newObj (key, value) {
      return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
    }
    
    var theTop = 'top'
    <something>.stop().animate(
      newObj(theTop, 10), 10
    )
    
    函数newObj(键,值){
    返回JSON.parse('{'+key+':'+JSON.stringify(value)+'}'))
    }
    var theTop='top'
    .stop().animate(
    newObj(theTop,10),10
    )
    
    如果希望对象键与变量名相同,ES 2015中有一个缩写。


    您可以这样做:

    var thetop = 'top';
    <something>.stop().animate(
        new function() {this[thetop] = 10;}, 10
    );
    
    var thetop='top';
    .stop().animate(
    新函数(){this[thetop]=10;},10
    );
    
    关于ES6和ES5之间的差异,我找不到一个简单的例子,所以我做了一个。两个代码示例创建完全相同的对象。但ES5示例也适用于较旧的浏览器(如IE11),而ES6示例则不适用

    ES6

    var matrix = {};
    var a = 'one';
    var b = 'two';
    var c = 'three';
    var d = 'four';
    
    matrix[a] = {[b]: {[c]: d}};
    
    ES5

    var matrix = {};
    var a = 'one';
    var b = 'two';
    var c = 'three';
    var d = 'four';
    
    function addObj(obj, key, value) {
      obj[key] = value;
      return obj;
    }
    
    matrix[a] = addObj({}, b, addObj({}, c, d));
    

    您也可以这样尝试:

    var thetop = "top",
        obj = { [thetop]: 10 };
    
    console.log(obj.top); // -> 10
    
    让数组1=[{
    “说明”:“星期四”,
    “计数”:“1”,
    “日期”:“2019-12-05”
    },
    {
    “说明”:“星期三”,
    “计数”:“0”,
    “日期”:“2019-12-04”
    }]
    让res=array1.map((值,索引)=>{
    返回{[value.description]:{count:value.count,date:value.date}
    })
    
    控制台日志(res)
    更新:正如一位评论者所指出的,任何支持箭头函数的JavaScript版本都将支持
    ({[my])
    
    var matrix = {};
    var a = 'one';
    var b = 'two';
    var c = 'three';
    var d = 'four';
    
    function addObj(obj, key, value) {
      obj[key] = value;
      return obj;
    }
    
    matrix[a] = addObj({}, b, addObj({}, c, d));
    
    myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
    
    {
        [`filter[${query.key}]`]: query.value,  // 'filter[foo]' : 'bar'
    }