如何在nodejs中将项目添加到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19084570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add items to array in nodejs
提问by Ben Scarberry
How do I iterate through an existing array and add the items to a new array.
如何遍历现有数组并将项目添加到新数组。
var array = [];
forEach( calendars, function (item, index) {
array[] = item.id
}, done );
function done(){
console.log(array);
}
The above code would normally work in JS, not sure about the alternative in node js. I tried .pushand .splicebut neither worked.
上面的代码通常可以在 JS 中工作,不确定node js. 我试过了.push,.splice但都没有奏效。
回答by nkron
Check out Javascript's Array APIfor details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:
查看Javascript 的 Array API以了解有关 Array 方法的确切语法的详细信息。修改您的代码以使用正确的语法是:
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:
您还可以使用该map()方法生成一个 Array,其中填充了对每个元素调用指定函数的结果。就像是:
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 letor constinstead of varand the =>syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):
而且,由于 ECMAScript 2015 已经发布,您可能会开始看到使用let或const代替创建函数var的=>语法的示例。以下与前面的示例等效(除非旧节点版本可能不支持它):
let array = calendars.map(item => item.id);
console.log(array);
回答by Gaurang Jadia
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.
这是一个示例,它可以为您提供一些提示以遍历现有数组并将项目添加到新数组。我使用 UnderscoreJS 模块作为我的实用程序文件。
You can download from (https://npmjs.org/package/underscore)
您可以从 ( 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);
回答by user6335419
var array = [];
//length array now = 0
array[array.length] = 'hello';
//length array now = 1
// 0
//array = ['hello'];//length = 1

