如何将项目添加到nodejs中的数组

我如何遍历现有的数组,并将项目添加到一个新的数组。

var array = []; forEach( calendars, function (item, index) { array[] = item.id }, done ); function done(){ console.log(array); } 

上面的代码通常在JS中工作,不知道node js的替代scheme。 我试过.push.splice但都没有工作。

有关数组方法的确切语法的详细信息,请查阅Javascript的数组API 。 修改你的代码来使用正确的语法是:

 var array = []; calendars.forEach(function(item) { array.push(item.id); }); console.log(array); 

您也可以使用map()方法来生成一个数组,其中填充了在每个元素上调用指定函数的结果。 就像是:

 var array = calendars.map(function(item) { return item.id; }); console.log(array); 

而且,由于ECMAScript 2015已经发布,您可能会开始使用letconst代替var=>语法来创build函数。 以下内容等同于前面的示例(旧节点版本中可能不支持此function):

 let array = calendars.map(item => item.id); console.log(array); 

这里是一个例子,它可以给你一些提示来遍历现有的数组,并添加项目到新的数组。 我使用UnderscoreJS模块作为我的实用程序文件。

你可以从( https://npmjs.org/package/underscore

 $ npm install underscore 

这里是一小段演示如何做到这一点。

 var _ = require("underscore"); var calendars = [1, "String", {}, 1.1, true], newArray = []; _.each(calendars, function (item, index) { newArray.push(item); }); console.log(newArray); 
 var array = []; //length array now = 0 array[array.length] = 'hello'; //length array now = 1 // 0 //array = ['hello'];//length = 1