如何在nodejs中向项目添加项目 [英] How to add items to array in nodejs

查看:112
本文介绍了如何在nodejs中向项目添加项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何遍历现有数组并将项添加到新数组中。

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);
}

以上代码通常可以在JS中使用,不确定 node js 。我尝试过 .push .splice ,但都没有用。

The above code would normally work in JS, not sure about the alternative in node js. I tried .push and .splice but neither worked.

推荐答案

查看 Javascript的Array API ,了解有关Array方法的确切语法的详细信息。修改代码以使用正确的语法将是:

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);

您还可以使用 map()生成一个数组的方法,该数组填充了在每个元素上调用指定函数的结果。类似于:

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);

而且,自ECMAScript 2015发布以来,您可能会开始看到使用的示例让 const 而不是 var => 创建函数的语法。以下内容与上一个示例等效(旧版节点版本可能不支持):

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);

这篇关于如何在nodejs中向项目添加项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆