javascript - 返回值作为对象属性

标签 javascript arrays javascript-objects

我必须编写一个函数,它接受一个数组并返回一个对象,其中数组的第一个元素作为对象的键,数组的最后一个元素作为对象的值。

以下是提出的挑战:

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/

相关文章:

javascript - 如何使用回调函数在 TypeScript 中保留词法范围

javascript - 这个 setTimeout 是如何工作的?什么是 49221 以及 console.log.bind 是如何工作的?

javascript - 错误 : The client-side rendered virtual DOM tree is not matching server-rendered

javascript - 更新控件模糊的 ValidationSummary 列表?

c++ - 通过指针将多数组传递给函数

javascript - 如何声明对象的属性,即获取 HTML 元素的方法?

arrays - 矩阵 block 索引

javascript - LoDash _.has 用于多个键

javascript - 强制 JavaScript 方法在迭代中使用类的属性而不是当前对象的属性

javascript - native 对象和宿主对象有什么区别?