我想在Javascript中创建一个函数,它以数组作为参数并返回一个对象列表。我有一个像这样的数组:
var arr= [10,20,30];
console.log(listFunction(arr));
结果应如下所示:
{'val':10, 'restList':{'val':20, 'restList':{'val':30,'restList':'null'}}}
我尝试过forEach()函数:
function listFunction(parentArr) {
var listOfObjects = [];
parentArr.forEach(function (entry, thisArg) {
var singleObj = {}
singleObj['val'] = entry;
singleObj['restList'] = singleObj;
listOfObjects[thisArg] = singleObj;
});
return listOfObjects;
};
答案 0 :(得分:4)
您需要使用递归函数:
function listFunction(arr){
if(arr.length == 0){
return null;
}else{
return {val: arr[0], restList: listFunction(arr.slice(1,arr.length))};
}
}
答案 1 :(得分:0)
这是Lisp风格的递归列表算法。
var recursiveList = function (array) {
return recursiveListHelper(arr, {});
};
var recursiveListHelper = function (array, obj) {
if (array.length === 0) //stopping condition
return null;
var car = array[0]; //current element
var cdr = array.slice(1); //rest of list
obj = {val: car};
obj.restList = recursiveListHelper(cdr, obj);
return obj;
};
您提到要避免使用Array.slice
。此解决方案使用数组索引而不是拆分为子数组。
var recursiveIndexed = function (array) {
return recursiveIndexedHelper(array, {}, 0);
};
var recursiveIndexedHelper = function (array, obj, index) {
if (index == array.length)
return null;
var car = array[index];
obj = {val: car };
obj.restList = recursiveIndexedHelper(array, obj, index + 1);
return obj;
};
以plunker为例。