问题描述
我需要获取给定数组中的第一个和最后一个元素,并返回一个对象,其中第一个元素作为键,最后一个元素作为值。
I need to take the first and last element in a given array and return an object with the first element as the key and the last as the value.
这是我的代码:
function transformFirstAndLast(array) {
array=[];
var object={};
object[key]=value;// make object
var key=array[0];
var value=array[array.length-1];
return object;} // return object
无论出于何种原因,它都是在对象内返回undefined。我发誓今天早上工作......
for whatever reason, it's returning undefined inside the object. I swear it was working this morning...
我一直在尝试:
function transformFirstAndLast(array) {
array=[];
var object = {};
object[array[0]] = array[array.length-1];}
但是在没有构建对象的情况下返回undefined。
but that's returning undefined without so much as an object being built.
推荐答案
您在函数开始时重新声明数组
。
You're redeclaring array
at the beggining of your function.
此外,在我看来,使用array和object作为变量名称是一个坏主意。只是一个错字可能会让你弄乱阵列和对象。这可能有副作用。
Besides, in my opinion, using "array" and "object" as variable names is a bad idea. Just a typo could get you messing up with Array and Object. And that might have side effects.
这是使用array.shift()和array.pop()方法的用例的功能小提琴。
Here's a functional fiddle for your use case using array.shift() and array.pop() methods.
var myArray=['one','two','three','four'];
function buildObject(arr) {
var myObject={},
key=arr.shift(),
val=arr.pop();
myObject[key]=val;
return myObject;
}
console.log(buildObject(myArray));
这篇关于数组到对象第一个和最后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!