在JavaScript对象列表的末尾添加元素 [英] Add an element at the end of a list of objects in JavaScript
本文介绍了在JavaScript对象列表的末尾添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的列表作为输入:
I have a list like this as an input:
{value: 1, rest: {value: 2, rest: null}}
我想在列表中添加一个元素并将其放置以便获得以下输出:
I want to add an element to the list and place it in order to have this output:
{value: 1, rest: {value: 2, rest: {value 3, rest:null}}}
我设法使用以下函数在元素的开头添加了元素,但是我应该如何使其在元素的结尾添加元素?谢谢.
I managed to add the element at the beginning using the following function but how should I make it to add the element at the ending? Thanks.
function prepend(elem, list){
list = {value:elem, rest:list};
return list;
}
console.log(prepend(3, {value: 1, rest: {value: 2, rest: null}}));
输出为: {value:3,rest:{value:1,rest:{value 2,rest:null}}}
推荐答案
尝试一下.我做了一个递归函数.
Try this. I made a recursive function.
function prepend(elem, list){
if (list.rest == null)
list.rest = {value:elem, rest:null};
else
prepend(elem, list.rest);
return list;
}
在所有情况下都可以使用此功能.
This function can be used in all cases.
这篇关于在JavaScript对象列表的末尾添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文