我正在尝试编写一个将字符串数组作为输入的函数。该函数应返回一个具有 (1) 键、值对的对象。数组的第一个元素应该是属性名称,数组的最后一个元素应该是它的键。
function transformFirstAndLast(array){
return {`${array[0]}`: array[length-1];}
}
以上给了我一个错误。有人可以详细解释为什么这不起作用吗?我想避免创建单独的变量来存储第一个和最后一个数组索引中的值。
最佳答案
您的问题实际上归结为“我可以将表达式用作对象文字中的键吗?”
答案是肯定的(从 es6 开始):
function yell(template, ...parts) {
return parts[0] + '!';
}
function foo() {
return 'bar';
}
class Person {
constructor(first, last) {
this.first = first;
this.last = last;
}
toString() {
return `${this.first} ${this.last}`;
}
}
let names = ['Abe'];
let my_obj = {
[3+5]: 'some_value',
[yell `${foo()}`]: foo(),
[names[0]]: 64,
[new Person('Rafael', 'Cepeda')]: 25
};
console.log(my_obj);
只要表达式的计算结果为字符串,一切都是公平的。
关于javascript - 您可以在 javascript 中使用模板文字创建对象属性名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52845823/