![](/img/trans.png)
[英]Javascript - how to use a variable as a function *and* an object literal
[英]How to use a variable for a key in a JavaScript object literal?
为什么以下工作?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
而这不起作用:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
为了更清楚:目前我无法将 CSS 属性作为变量传递给动画 function。
{ 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
);
ES6 将ComputedPropertyName定义为对象文字语法的一部分,它允许您编写如下代码:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
您可以在每个主流浏览器的最新版本中使用这种新语法。
使用ECMAScript 2015 ,您现在可以使用括号符号直接在对象声明中执行此操作:
var obj = {
[key]: value
}
其中key
可以是返回值的任何类型的表达式(例如变量)。
所以这里你的代码看起来像:
<something>.stop().animate({
[thetop]: 10
}, 10)
在用作键之前将评估thetop
的位置。
ES5 引用说它不应该工作
注意:ES6 的规则已更改: https ://stackoverflow.com/a/2274327/895245
规格:http: //www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
物业名称:
- 标识符名称
- 字符串字面量
- 数字字面量
[...]
产品 PropertyName : IdentifierName 的评估如下:
- 返回包含与 IdentifierName 相同的字符序列的字符串值。
产生式 PropertyName : StringLiteral 的评估如下:
- 返回 StringLiteral 的 SV [字符串值]。
产生式 PropertyName : NumericLiteral 的评估如下:
- 令 nbr 为形成 NumericLiteral 值的结果。
- 返回到字符串(nbr)。
这意味着:
{ theTop : 10 }
与{ 'theTop' : 10 }
PropertyName
theTop
是一个IdentifierName
,因此它被转换为'theTop'
字符串值,即 'theTop 'theTop'
的字符串值。
不可能用变量键编写对象初始化器(文字)。
仅有的三个选项是IdentifierName
(扩展为字符串文字)、 StringLiteral
和NumericLiteral
(也扩展为字符串)。
ES6 / 2020
如果您尝试使用来自任何其他来源的“key:value”将数据推送到对象,您可以使用以下内容:
let obj = {}
let key = "foo"
let value = "bar"
obj[`${key}`] = value
// A `console.log(obj)` would return:
// {foo: "bar}
// A `typeof obj` would return:
// "object"
希望这可以帮助某人:)
我使用以下内容将具有“动态”名称的属性添加到对象:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key
是新属性的名称。
传递给animate
的属性对象将是{left: 20, width: 100, top: 10}
这只是使用其他答案推荐的所需[]
表示法,但代码行数更少!
在变量周围添加方括号对我很有用。 尝试这个
var thetop = 'top';
<something>.stop().animate(
{ [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));
更新:正如评论者指出的那样,任何支持箭头函数的 JavaScript 版本也将支持({[myKey]:myValue})
,所以这个答案没有实际的用例(事实上,它可能会出现一些奇怪的问题极端情况)。
不要使用下面列出的方法。
我不敢相信这还没有发布:只需使用带有匿名评估的箭头函数!
完全非侵入性,不会混淆命名空间,并且只需要一行:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
演示:
var myKey="valueof_myKey"; var myValue="valueof_myValue"; var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue); console.log(myNewObj);
在还不支持新的 {[myKey]: myValue}
语法的环境中很有用,例如——显然;我刚刚在我的 Web 开发者控制台上验证了它——Firefox 72.0.1,发布于 2020 年 1 月 8 日。 我的立场是正确的; 只需将东西放在括号中即可。
(我相信您可能会做出一些更强大/可扩展的解决方案或任何涉及巧妙使用reduce
的解决方案,但在这一点上,您可能会更好地将 Object-creation 分解为它自己的函数而不是强制干扰全部内联)
自从 OP 十年前提出这个问题以来,这并不重要,而是为了完整起见并证明它是如何准确地回答所述问题,我将在原始上下文中展示这一点:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
你也可以这样尝试:
const arr = [{ "description": "THURSDAY", "count": "1", "date": "2019-12-05" }, { "description": "WEDNESDAY", "count": "0", "date": "2019-12-04" }] const res = arr.map(value => { return { [value.description]: { count: value.count, date: value.date } } }) console.log(res);
给定代码:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
翻译:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
如您所见, { thetop : 10 }
声明没有使用变量thetop
。 相反,它使用名为thetop
的键创建一个对象。 如果您希望键是变量thetop
的值,那么您必须在thetop
周围使用方括号:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
ES6 引入了方括号语法。 在早期版本的 JavaScript 中,您必须执行以下操作:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
2020 年更新/示例...
一个更复杂的例子,使用括号和文字......你可能不得不做的事情,例如 vue/axios。 将文字包裹在括号中,所以
[`...`]
{
[`filter[${query.key}]`]: query.value, // 'filter[foo]' : 'bar'
}
分配键的 ES5 实现如下:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
我附上了一个我用来转换为裸对象的片段。
var obj = { 'key1': 'value1', 'key2': 'value2', 'key3': [ 'value3', 'value4', ], 'key4': { 'key5': 'value5' } } var bareObj = function(obj) { var objArgs, bareObj = Object.create(null); Object.entries(obj).forEach(function([key, value]) { var objArgs = ( (objArgs = {}), (objArgs[key] = { value: value }), objArgs); Object.defineProperties(bareObj, objArgs); }); return { input: obj, output: bareObj }; }(obj); if (!Object.entries) { Object.entries = function(obj){ var arr = []; Object.keys(obj).forEach(function(key){ arr.push([key, obj[key]]); }); return arr; } } console(bareObj);
如果您希望对象键与变量名相同,ES 2015 中有一个简写方式。ECMAScript 2015 中的新符号
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
你可以这样做:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
这样您也可以实现所需的输出
var jsonobj={}; var count=0; $(document).on('click','#btnadd', function() { jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()}); count++; console.clear(); console.log(jsonobj); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span>value 1</span><input id="txtone" type="text"/> <span>value 2</span><input id="txttwo" type="text"/> <button id="btnadd">Add</button>
您可以为 ES5 执行以下操作:
var theTop = 'top'
<something>.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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.