我有一个具有名为'type'的属性的对象。此类型是对象中另一个属性的名称。我可以使用Object Literal Syntax在不将声明分成多个部分的情况下实现所需的输出。这就是我所拥有的,感谢帮助。
// desired output
// {
// name: 'Tom Ford',
// type: 'random-type',
// 'random-type': {
// title: 'Blah',
// amount: 2000
// }
// }
var thisRefTest = {
name: 'Tom Ford',
type: getRandomType(),
[this.type]: {
title: 'Blah',
amount: 2000
}
}
console.log('thisRefTest', thisRefTest)
// output:
// {
// "name": "Tom Ford",
// "type": "random-type",
// "undefined": {
// "title": "Blah",
// "amount": 2000
// }
// }
var funcRefTest = {
name: 'Tom Ford',
type: getRandomType(),
[function () {
return this.type;
}()]: {
title: 'Blah',
amount: 2000
}
}
console.log('funcRefTest', funcRefTest)
// output:
// {
// "name": "Tom Ford",
// "type": "random-type",
// "undefined": {
// "title": "Blah",
// "amount": 2000
// }
// }
function getRandomType(){
return 'random-type';
}
答案 0 :(得分:0)
仅当您要定义具有值的变量
时var type = getRandomType();
var thisRefTest = {
name: 'Tom Ford',
type: type,
[type]: {
title: 'Blah',
amount: 2000
}
};
事实是在实例化时没有对象。
Javascript解释器无法引用对象中的属性,即未创建,但不符合相应的右括号}
。