我必须编写一个函数,它接受一个数组并返回一个对象,其中数组的第一个元素作为对象的键,数组的最后一个元素作为对象的值。
以下是提出的挑战:
Write a function 'transformFirstAndLast' that takes in an array, and returns an object with: 1) the first element of the array as the object's key, and 2) the last element of the array as that key's value.
输入示例:
['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce']
函数的返回值(输出):
{
Queen : 'Beyonce'
}
不要更改输入数组。假设输入数组中的所有元素均为“string”类型。
请注意,输入数组可能具有不同数量的元素。您的代码应该灵活地适应这一点。
例如它应该处理如下输入:
['Kevin', 'Bacon', 'Love', 'Hart', 'Costner', 'Spacey']
函数的返回值(输出):
{
Kevin : 'Spacey'
}
起始代码
function transformFirstAndLast(array) {
// your code here
}
这是我的代码
function transformFirstAndLast() {
//Take in an array
array = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'];
//Return an object with:
return {
//element 1 element 2
stuckHere : array[array.length-1],
};
}
//call function
transformFirstAndLast();
非常感谢任何帮助!
最佳答案
按照描述使用计算属性键 here :
function transformFirstAndLast(array) {
return {[array[0]]: array[array.length - 1]};
}
console.log(transformFirstAndLast(['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce']));
对象属性键[array[0]]
是根据第一个数组元素array[0]
计算的。它的值是最后一个数组元素array[array.length - 1]
。
您应该考虑将 array
作为参数传递给 transformFirstAndLast
函数(如此处所示),以符合挑战提供的函数签名。
关于javascript - 返回值作为对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44081725/