const arr = [1,2,3];

let arrReverse = [];

for ( let i =arr.length -1; i >=0 ; i --){
	arrReverse.push(arr[i]);
 }
 
 const arrReverse2 = arr.reverse(); // 원본 배열도 순서가 뒤집힌다.
 
 const arrReverse3 = [...arr].reverse(); // 원본배열 복사후 배열순서 바꾸기

Spread operator(스프레드 연산자,  ... )

=> 배열/객체 를 펼쳐서 각 요소를 분리 후, 매개변수 목록으로 만든 다음에  매개변수를 새로운 배열/객체 에 할당함.

const arr = [1,2,3];
const obj = { a: 1, b: 2, c: 3 };
// copy
let arrayCopy2 = array.assign([], arr);
let objectCopy2 = Object.assign({}, obj);
// spread operator
const arrayCopy = [...arr] // array copy
cosnt objectCopy = {...obj} // object copy

const str = "hello"
const strStread = [...str] // ["h", "e", "l", "l", "o"]

=> 복사를 한 배열/객체 안의 요소는 원본과 같다.

=> 하지만, 원본의 값이 바뀌어도 복사된 배열/객체 의 값은 변하지 않는다. ( python 에서 copy.deepcopy 와 같음)

 

참고 :https://ko.javascript.info/rest-parameters-spread#spread-syntax

 

나머지 매개변수와 스프레드 문법

 

ko.javascript.info

 

'프로그래밍 > JavaScript' 카테고리의 다른 글

[JS] call, apply, bind  (0) 2024.03.06
객체(Object), 객체 메소드  (0) 2023.08.03
array.reduce()  (0) 2023.07.30
Class  (0) 2023.07.13
Functions - arrow, map, filter  (0) 2023.07.12

array.reduce(callback, initialValue) 로 구성

 

callback - > (accumulator, currentValue, currentIndex, array)

initalValue (option)

를 구성해서 array 에있는 값을 모두 더 할때 사용된다.

 

const arr = [1,2,3];

const result1 = arr.reduce((acc,value) => acc += value); //6

const result2 = arr.reduce((acc,value) => {acc += value}, 10); //16
const result2_1 = arr.reduce((acc,value) => acc += value, 10); //16

 

 

(참고) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

 

Array.prototype.reduce() - JavaScript | MDN

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the a

developer.mozilla.org

 

'프로그래밍 > JavaScript' 카테고리의 다른 글

객체(Object), 객체 메소드  (0) 2023.08.03
배열 뒤집기  (0) 2023.07.30
Class  (0) 2023.07.13
Functions - arrow, map, filter  (0) 2023.07.12
콜백(callback)함수  (0) 2023.07.12
  • 객체를 효율적이고 안전하게 만들기 위해서 만들어진 문법
  • 클래스는 상태( = 속성, 필드, 특성, 멤버변수)와 행위 (기능, 메서드, 함수) 를 가지고 있다. 
  • 실생활에서 사용하는 개념(사물, 사람, 기계 등을) 코드로 표현하기 위한 수단..

구성:  클래스 생성자 인스턴스

  • 클래스 = 설계도
  • 인스턴스 = 설계도를 통해 만들어진 실체화된 객체
  • 생정자 =  인스턴스를 만들 때 사용하는 것

(예시) 자동차 클래스

 

= 선언된 클래스를 다른 파일에 불러오는 방법 :: python에 있는 import 기능

-- makeCarClass.js -- 

module.exports = makeCarClass;< 선언된 클래스가 있는 코드명>

 

-- app.js ----

const Car = require('./makeCarCalss) < 코드명을 입력해서 클래스 호출>

const car = new Car("아반떼", 90);

 

※ 한 코드 파일에 여러가지( 객체, 배열, 함수, 클래스) 가 있다면

1. 앞에 export 붙여주면 된다.

2.  마지막에 module.exports= { 다시 사용 할 객체, 배열, 함수, 클래스}

//myTest.js

export const myArr = [1,2,3,4];
export const myObject = {name: a, age: 30};
export function myfuntion(){
  for (let i = 1; i < 10; i++) {
	//code..
  }
}
export class Car{
	//code...
}

// 앞에 export를 안적었다면
module.export ={myArr, myObject, myfunctioin, Car}
// app.js
const { myArr, Car} = require('./myTest');


// 아래는 새로운 문법인가? 
// https://ko.javascript.info/import-export
import * as test from "./myTest.js" //전부 호출
import {myArr, Car} from "./myTest.js" // 호출하고 싶은것만

 

 

클래스  + 객체

▶객체를 class의 입력으로 사용할 때 아래와 같이 객체의 key를 이용해서 각 key에 있는 value값을 받을 수 있다.

(비구조화 할당 활용)

class Student{
    constructor({name, krScore, enScore}){
        this.name = name;
        this.krScore = krScore;
        this.enScore = enScore;
    }
    //code...
 }

'프로그래밍 > JavaScript' 카테고리의 다른 글

배열 뒤집기  (0) 2023.07.30
array.reduce()  (0) 2023.07.30
Functions - arrow, map, filter  (0) 2023.07.12
콜백(callback)함수  (0) 2023.07.12
Function(함수)  (0) 2023.07.11

화살표 함수 Arrow function

  • 기본형태
let functionName = (argument1, arg2, ...argN) => expression;

let double = (n) => n * 2;

let double = function(n) { 
	return n*2;
 }
  • forEach(), map(), filter() 속에서도 가능
array.forEach(element => {
    //code
});
  • array.filter() 는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환
const result = studentsInfo.filter(({ score }) => score >= 90);

//https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
  • array.map()  배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환
names = result.map(({ name }) => name);

//https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);

'프로그래밍 > JavaScript' 카테고리의 다른 글

array.reduce()  (0) 2023.07.30
Class  (0) 2023.07.13
콜백(callback)함수  (0) 2023.07.12
Function(함수)  (0) 2023.07.11
배열 과 객체 의 for loop  (0) 2023.07.09

<정의>

함수안에 파라미터로 들어가는 함수

<용도>

순차적으로 실행하고 싶을때 씀

 

<사용 예시>

function sortTest(ls,cb){
	ls.sort((previous, current) => previous-current);
	cb("Assending",ls)
    ls.sort((previous, current) => current-previous));
    cb("Dessending", ls)
    
}

function print(message, ls){
	consol.log(`${message}`)
    for(const i of ls){
    	consol.log(`call back test: ${i}`);
        }
}

let tempArr = [1,5,8,3,10]
sortTest(tempArr,print)

// for each

// 기본형태
array.forEach(element => {
   // code 
});


tempArr.forEach((value, index, array) => console.log(tempArr[index]));

//풀어서 쓰면 아래와 같다.
const test = function (value, index, array) {
  console.log(tempArr[index]);
};
tempArr.forEach(test);

'프로그래밍 > JavaScript' 카테고리의 다른 글

Class  (0) 2023.07.13
Functions - arrow, map, filter  (0) 2023.07.12
Function(함수)  (0) 2023.07.11
배열 과 객체 의 for loop  (0) 2023.07.09
var, let, const  (0) 2023.07.09

+ Recent posts