In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys : Object Initializer spec .(在JavaScript的新ES2015标准 (以前称为ES6)中,可以使用计算键创建对象 : Object Initializer spec 。)
The syntax is:(语法为:)
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:(如果应用于OP的场景,它将变成:)
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity .(注意: 浏览器兼容性仍然需要编译器 。)
Using Babel or Google's traceur , it is possible to use this syntax today .(使用Babel或Google的traceur , 今天可以使用此语法 。)
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.(在早期的JavaScript规范(ES5及更低版本)中,对象文字中的键始终按字面意义解释为字符串。)
To use a "dynamic" key, you have to use bracket notation :(要使用“动态”键,必须使用方括号表示法 :)
var obj = {};
obj[myKey] = value;
In your case:(在您的情况下:)
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…