developer tip

nodejs의 배열에 항목을 추가하는 방법

copycodes 2020. 12. 29. 07:21
반응형

nodejs의 배열에 항목을 추가하는 방법


기존 배열을 반복하고 새 배열에 항목을 추가하는 방법은 무엇입니까?

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

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

위의 코드는 일반적으로 JS에서 작동하지만 node js. 나는 시도하지 .push하고 .splice있지만, 어느 쪽도했다.


Array 메서드의 정확한 구문에 대한 자세한 내용은 Javascript의 Array API확인하십시오 . 올바른 구문을 사용하도록 코드를 수정하면 다음과 같습니다.

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

console.log(array);

map()메서드를 사용하여 각 요소에 대해 지정된 함수를 호출 한 결과로 채워진 Array를 생성 할 수도 있습니다 . 다음과 같은 것 :

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

console.log(array);

그리고 ECMAScript 2015가 출시 된 이후로 함수 생성을위한 구문 과 함께 let또는 const대신 사용하는 예제를 볼 수 있습니다. 다음은 이전 예제와 동일합니다 (이전 노드 버전에서는 지원되지 않을 수 있음).var=>

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

다음은 기존 배열을 반복하고 새 배열에 항목을 추가하는 몇 가지 힌트를 제공 할 수있는 예입니다. UnderscoreJS Module을 사용하여 유틸리티 파일로 사용합니다.

( 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

참조 URL : https://stackoverflow.com/questions/19084570/how-to-add-items-to-array-in-nodejs

반응형