-
[NodeJS] ArrayNodeJS/Basic 2022. 9. 14. 17:22
다양한 자료를 하나의 범주 안에 넣고 인덱싱(번호)를 이용해 컨트롤 하는 변수
var array = [273, 'string', true, function(){}, {}, [150,170]]; console.log(array[0]); console.log(array[1]); console.log(array[2]); console.log(array[3]); console.log(array[4]); console.log(array[5]); console.log(array);
var arr = ['a', 'b', 'c']; console.log('변경 전: '+arr); arr.push('d'); console.log('배열의 끝에 요소 추가: '+arr); arr.unshift('A'); console.log('배열의 앞쪽에 요소 추가: '+arr); arr.splice(2, 0, 'B'); console.log('index 2(\'b\')의 위치에 요소를 추가: '+arr); console.log(); arr = ['a', 'b', 'c', 'd']; console.log('변경 전: '+arr); arr.splice(2, 0, 'C', 'D'); console.log('index 2의 위치(\'c\')에 2개의 요소를 추가: '+arr);
arr = ['a', 'b', 'c', 'd', 'f']; console.log('변경 전: '+arr); // index 2부터 1개의 요소('c')를 제거 arr.splice(2, 1); console.log('변경 후((index 2부터 1개의 요소(\'c\')를 제거): '+ arr); arr = ['a', 'b', 'c', 'd', 'f']; console.log('변경 전: '+arr); // index 1부터 1개의 요소('b', 'c')를 제거 arr.splice(1, 2); console.log('변경 후((index 1부터 2개의 요소(\'b\', \'c\')를 제거): '+ arr); console.log();
// delete로 배열의 요소를 삭제할 경우 값은 삭제되고 자리요소는 존재함 var arr = ['a', 'b', 'c', 'd', 'f']; console.log('변경 전: '+arr); delete arr[1]; console.log('변경 후(arr[1] 삭제): '+arr);
Object Array
// 생성자 함수로 배열의 요소 추가 function Student(name, korean, math, english, science){ // 속성 this.name = name; this.kor = korean; this.math = math; this.english = english; this.science = science; this.getSum = function(){ return this.kor + this.math + this.english + this.science; } // 메서드 this.getAvg = function(){ return this.getSum()/4; } this.toString = function(){ return `성명: ${this.name}, 총점: ${this.getSum()}, 평균: ${this.getAvg()}`; } } let students = []; // 비어 있는 배열을 생성 let obj1 = new Student('홍길동', 80, 65, 98, 78); // Student 객체 생성 students.push(obj1); // students 배열에 obj1 객체를 추가 students.push(new Student('홍길남', 88, 88, 99, 75)); students.push(new Student('홍길북', 85, 60, 85, 70)); students.push(new Student('홍길동', 65, 60, 75, 80)); students.push(new Student('이길동', 75, 95, 85, 90)); students.push(new Student('박길동', 90, 80, 75, 90)); // 배열이 for문에 사용되면 객체처럼 멤버변수 이름들이 전달되는 것이 아니라 // 각 배열 요소의 인덱스 값들이 1에 전달되어 반복실행이 진행함 for(var i in students){ console.log(students[i].toString()); } console.log();
// 객체에 문자열 연산과 함수와 변수를 활용 let sayNode = function(){ console.log('Node'); }; let myName = "NodeJS"; let oldObject = { // myName : 'NodeJS', // myName : myName, // 첫번재 myNmae: 멤버변수, 두번재 myName: 일반변수 // 멤버변수에 대입될 값을 저장하고 있는 일반 변수의 이름이 같다면 // 아래와 같이 한번만 써서 표현될 수 있음 myName, // myName: myName, 이렇게 쓴 것과 동일함 /*sayNode: function(){ console.log('Node'); }*/ // sayNode: sayNode, sayNode, sayJS:function(){ console.log('JS'); }, } // 키(멤버변수)이름과 value변수명이 같으면 한번만 써도(:생략) 무방함 console.log(oldObject.myName); oldObject.sayNode(); oldObject.sayJS();
let strVar = 'ES'; oldObject[strVar+'6'] = 'Fantastic'; // 멤버 변수이름을 String 데이터의 조합으로 만듦. // 'ES6'라는 멤버변수 생성. 문자열 연산에 의해 변수이름을 조합한 예 console.log(oldObject.ES6); // const 변수로 객체 생성 const newObject = { myName, sayJS: function(){console.log('JS');}, sayNode, }; newObject.ES6='Fantastic'; // const로 생성한 객체는 변수가 객체로 고정되어 다른 데이터형으로 수정할 수 없을 뿐 // 멤버의 변화까지 고정된 건 아님 // newObject = ... -> 변수에 다른 값 대입 -> error // new Object.???=xxx -> 객체내에 새로운 멤버 생성 -> 정상실행 console.log(newObject.myName); // -> myName newObject.sayNode(); // -> Node newObject.sayJS(); // -> JS console.log(newObject.ES6); // -> Fantastic
객체의 구조분해: 객체 내부의 멤버변수 또는 멤버메서드를 별도의 변수에 따로 저장하여 별도로 사용하기 위한 문법
const sayJ = newObject.sayJS; // 객체 내의 함수를 별도의 변수에 저장 sayJ(); const sayN = newObject.sayNode; sayN(); var es6 = newObject.ES6; console.log(newObject.ES6); console.log(es6);
// 객체의 구조 분해를 하지 말아야 하는 경우 // -this를 사용하는 객체 const candyMachine = { status: { name: 'node', count: 5, }, getCandy(){ this.status.count--; return this.status.count; }, }; console.log(candyMachine.getCandy()); var getCandy = candyMachine.getCandy; var count = candyMachine.status.count; // getCandy(); -> error // Cannot read properties of undefined(reading 'count') console.log(count); // 객체 내의 메서드가 구조 분해되는 순간 안에 있던 this를 사용할 수 없게 되므로 // 그 안의 count 또한 없는 변수가 되어 오류 발생
'NodeJS > Basic' 카테고리의 다른 글
[NodeJS] Promise, Await (0) 2022.09.14 [NodeJS] Arrow Function (0) 2022.09.14 [NodeJS] Object (0) 2022.09.14 [NodeJS] var, const, let, template string (0) 2022.09.14 [NodeJS] 설치, 콘솔실행 (0) 2022.09.14