为什么下面的工作?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
而这不起作用:
var thetop = 'top';
<something>.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
);
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:
- 标识符名称
- 字符串字面量
- 数字文学
[...]
生产PropertyName:IdentifierName的评估如下:
- 返回包含与IdentifierName相同的字符序列的String值。
生产PropertyName:StringLiteral的评估如下:
- 返回StringLiteral的SV [String value]。
生产PropertyName:NumericLiteral的评估如下:
- 令nbr为形成NumericLiteral值的结果。
- 返回ToString(nbr)。
这意味着:
-
{ theTop : 10 }
与...完全相同{ 'theTop' : 10 }
的
PropertyName
theTop
是一个IdentifierName
,所以它被转换为'theTop'
字符串值,这是的字符串值'theTop'
。 -
不能使用变量键编写对象初始化程序(文字)。
仅有的三个选项是
IdentifierName
(扩展为字符串文字)StringLiteral
,和NumericLiteral
(也扩展为字符串)。
我已使用以下方法向对象添加具有“动态”名称的属性:
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));
给定代码:
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 }
声明没有使用variable 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'
}
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"
希望这可以帮助某人:)
分配密钥的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
);
您也可以这样尝试:
let array1 = [{
"description": "THURSDAY",
"count": "1",
"date": "2019-12-05"
},
{
"description": "WEDNESDAY",
"count": "0",
"date": "2019-12-04"
}]
let res = array1.map((value, index) => {
return { [value.description]: { count: value.count, date: value.date } }
})
console.log(res);
我不敢相信这还没有发布:只需在匿名评估中使用箭头符号即可!
完全是非侵入性的,不会与名称空间混淆,仅需一行:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
演示:
在尚不支持新{[myKey]: myValue}
语法的环境中很有用,例如-很明显;我刚刚在2020年1月8日发布的Web开发者控制台Firefox 72.0.1上对其进行了验证。
(我确定您可能会提出一些更强大/可扩展的解决方案,或者涉及聪明地使用的任何方法reduce
,但是到那时,最好将Object-creation分解为自己的函数,而不是强迫性地阻塞它,这可能会更好。全部内联)
这不是问题,因为OP按十年前问过,但为了完整性,并证明它是多么确切 的答案,因为说,我会在原来的背景下显示此问题:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(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
)
文章标签:javascript , jquery , object-literal , properties , variables
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!