gpt4 book ai didi

javascript - 无法创建以数组索引作为键和值的 JS 对象?

转载 作者:行者123 更新时间:2023-11-30 11:28:56 24 4
gpt4 key购买 nike

任务:将数组转换为具有一个键值对的对象,其中第一个数组项是键,最后一个数组项是值。

例如,[1,2,3] 应转换为 {1: 3}

我无法让它工作:

function transformFirstAndLast(array) {
var firstLast = {
array[0]: array[-1]
};
return firstLast
}

但仅作为:

function transformFirstAndLast(array) {
var firstLast = {};
firstLast[array[0]] = array[array.length - 1];
return firstLast
}

...为什么第一个不起作用?为什么不能为键和值索引数组?

最佳答案

您可以弹出最后一个元素并为该对象获取一个计算属性。 (对于第一个元素,您可以采用 Array#shift ,如果您喜欢以相同的方式进行的话。)

function transformFirstAndLast(array) {
return { [array[0]]: array.pop() };
}

console.log(transformFirstAndLast([1, 2, 3]));

带有临时变量的 ES5。

function transformFirstAndLast(array) {
var temp = {};
temp[array[0]] = array.pop();
return temp;
}

console.log(transformFirstAndLast([1, 2, 3]));

关于javascript - 无法创建以数组索引作为键和值的 JS 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46956062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com