如何向 nodejs 中的数组添加项

如何迭代现有数组并将项添加到新数组中。

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


function done(){
console.log(array);
}

上面的代码通常在 JS 中工作,而在 node js中则不一定。我试了 .push.splice,但都不管用。

361241 次浏览

Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.

You can download from (https://npmjs.org/package/underscore)

$ npm install underscore

Here is small snippet to demonstrate how you can do it.

var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
newArray = [];


_.each(calendars, function (item, index) {
newArray.push(item);
});


console.log(newArray);

Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:

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


console.log(array);

You can also use the map() method to generate an Array filled with the results of calling the specified function on each element. Something like:

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


console.log(array);

And, since ECMAScript 2015 has been released, you may start seeing examples using let or const instead of var and the => syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):

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


//length array now = 0
array[array.length] = 'hello';
//length array now = 1
//            0
//array = ['hello'];//length = 1

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


console.log(array);