如何在javascript / Node.js中将数组添加到数组

时间:2018-08-03 07:53:35

标签: javascript node.js

我目前正在将node.js用于一个项目,如果可以的话,请提供帮助。忙于制作待办事项列表,并想将列表名称添加到numlists,这行得通吗?

rl.question(“您想做什么?”,函数(firstAnswer){

if(firstAnswer == '1'){

    var addList = [];
    var numLists = [];
    for( i = 0; i< numlists.length; i++){

        rl.question("What is the list's name?", function(listName){
            numLists[i] = listName;
            rl.question("Do you want to add another list?", function
        }



    }

}
    else if(firstAnswer == '2'){




    }
        else if(firstAnswer == '3'){




        }

2 个答案:

答案 0 :(得分:1)

据我了解,以下是您想要组合数组的答案。

var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);

儿童输出:[“塞西莉”,“孤独”,“埃米尔”,“托比亚斯”,“利纳斯”]

答案 1 :(得分:1)

还有另一种简便的方法来连接JavaScript中的数组:

var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = [...hege, ...stale];

输出将是:['Cecilie','Lone','Emil','Tobias','Linus']

这种方法的优点是您可以像这样在两个数组之间添加额外的项:

var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = [...hege, 'jon', ...stale, 'jeff'];

输出为:['Cecilie','Lone','jon','Emil','Tobias','Linus','jeff']