Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

javascript - 如何在nodejs中向项目添加项目(How to add items to array in 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);
}

The above code would normally work in JS, not sure about the alternative in node js .

(上面的代码通常可以在JS中使用,不确定node js的替代方法。)

I tried .push and .splice but neither worked.

(我试过.push.splice但都没有奏效。)

  ask by Ben Scarberry translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check out Javascript's Array API for details on the exact syntax for Array methods.

(查看Javascript的Array API ,了解有关Array方法的确切语法的详细信息。)

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.

(您还可以使用map()方法生成一个Array,其中填充了在每个元素上调用指定函数的结果。)

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.

(而且,自ECMAScript 2015发布以来,您可能会开始使用letconst而不是var=>语法来创建函数。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...