[ javascript ] 유용한 함수들 10가지 > javascript&jQuery

본문 바로가기
사이트 내 전체검색

javascript&jQuery

[ javascript ] 유용한 함수들 10가지

페이지 정보

작성자 웹지기 댓글 0건 조회 3,307회 작성일 21-02-15 22:58

본문

javascript 유용한 함수들 10가지

https://youtu.be/3CUjtKJ7PJg

 

// Q1. make a string out of an array

{

    const fruits = ['apple', 'banana', 'orange'];

    const result = fruits.join();

    console.log(result);

}

  

// Q2. make an array out of a string

{

    const fruits = 'apple, banana, melon, tomato';

    const result = fruits.split(",");

    console.log(result);

}


// Q3. make this array look like this: [5, 4, 3, 2, 1]

{

    const array = [1, 2, 3, 4, 5];

    const arrSort = array.reverse();

    console.log(arrSort);

    console.log(array);

}


// Q4. make new array without the first two elements

{

    const array = [1, 2, 3, 4, 5];

    const result = array.splice(2, 5);

    console.log(result);

    console.log(array);

}


class Student {

    constructor(name, age, enrolled, score) {

        this.name = name;

        this.age = age;

        this.enrolled = enrolled;

        this.score = score;

    }

}

const students = [

    new Student('A', 29, true, 45),

    new Student('B', 28, false, 80),

    new Student('C', 30, true, 90),

    new Student('D', 40, false, 66),

    new Student('E', 18, true, 88),

];


// Q5. find a student with the score 90

{

    console.clear();

    /*

    * 해당하는 배열만 찾아 낼 때 find()

    const result = students.find(function(student, index){

        //console.log(student, index);

        return student.score === 90;

    });

    */

    //arrow function expression 으로 변경

    const result = students.find((student) => student.score === 90);

    console.log(result);

}


// Q6. make an array of enrolled students

{

    console.clear();

    /*

    * 조건에 맞는 배열만을 가져오고 싶을 때 filter()

    const result = students.filter(function(student){

        //console.log(student);

        return student.enrolled === true;

    });

    */

    //arrow function expression 으로 변경

    const result = students.filter((student) => student.enrolled);

    console.log(result);

}


// Q7. make an array containing only the students' scores

// result should be: [45, 80, 90, 66, 88]

{

    console.clear();

    /*

    * 학생들의 점수만을 새로운 배열로 넣고 싶을 때 map()

    const result = students.map(function(student){

    //점수를 두배로 바꾸고 싶다면 return student.score * 2를 해주면 된다.

        return student.score;

    });

    */

    //arrow funtion expression 으로 변경

    const result = students.map((student) => student.score);

    console.log(result);

}


// Q8. check if there is a student with the score lower than 50

{

    console.clear();

    //배열의 조건이 만족할 때 출력하고 싶다면 some()

    /*

    const result = students.some(function(student) {

        return student.score < 50;

    });

    */

    //arrow function expression

    const result = students.some((student) => student.score < 50);

    console.log(result);


    //모든 배열의 조건이 만족하게 하고 싶다면 every()

    //some()처럼 사용하고 싶으면 !을 사용하면 된다.

    //const result2 = !students.every(function(student) {

    //    return student.score >= 50;

    //});

    /*

    * 이값은 모든 조건이 50보다 작은값이 아니므로 false

    const result2 = students.every(function(student) {

        return student.score < 50;

    });

    */

    //arrow function expression

    const result2 = !students.every((student) => student >= 50);

    console.log(result2);

}


// Q9. compute students' average score

{

    console.clear();

    //reduce는 어떤값을 돌면서 누적할 때 사용

    //reduceRight는 뒤에서 부터 반복해서 누적할 때 사용

    //reduce는 curr에 배열이 하나 하나씩 순차적으로 전달이 된다.

    //prev는 처음에는 배열의 첫번째값 두번째부터는 return 되어 오는 값을 받아 들인다.

    /*

    const result = students.reduce(function(prev, curr) {

        //console.log('------------');

        //console.log(prev);

        //console.log(curr);

        //return curr; 값의 전달 확인용

        //점수의 합을 구하므로 아래처럼 합을 해준다.

        return prev + curr.score;

    }, 0);

    */

    //arrow function expression

    const result = students.reduce((prev, curr) => prev+curr.score, 0);

    console.log(result/students.length);

}


// Q10. make a string containing all the scores

// result should be: '45, 80, 90, 66, 88'

{

    //점수에 대한 새로운 배열을 만든다.

    const result = students

        .map((student) => student.score) //학생들을 점수로 변환하고

        .filter((score) => score >= 50) //점수 50점 이상인 학생만 필터하고

        .join(); //조인을 해주면 된다.

    console.log(result);

}


// Bonus! do Q10 sorted in ascending order

// result should be: '45, 66, 80, 88, 90'

{

    const result = students

        .map((student) => student.score)

        .sort((a, b) => a - b ) //낮은 점수 먼저 부여주고 높은점수 부터 보고 싶다면 b-a로 수정하면된다.

        .join();

        console.log(result);

}

 

추천0 비추천0

댓글목록

등록된 댓글이 없습니다.

Total 63건 1 페이지
  • 63 [ javascript ] CDATA 사용 이유
  • 1) CDATA로 감싼 JAVASCRIPT부분이 의도치 않게 XML Parser 에 의해 잘못 인식되는 것을 막기 위함. 2) XHTML이 아닌 HTML로 인식되는 경우에도 JAVASCRIPT가 문제없이 동작하도록 하기 위함. 3) javascript안에서 태그를 사용할 경우 CDATA 선을 해줘서 오류처리를 막기 위함. 사용예제 &lt;script&gt; //&lt;![CDATA[ JAVASCRIPT //]]&gt; &lt;/scri...
  • 웹지기 01-20 3172 0 0 댓글 0
  • 62 [ javascript ] promise 를 async & await 로 쉽게 써보자
  • promise 를 async &amp; await 로 쉽게 써보자 //promise는 chaning가 가능하다. //체인이 많아 지면 복잡해진다. //async await 동기식으로 순서를 작성하는 것 처럼 간편하게 작성가능 //기존에 존재하는 promise 위에 간단한 api를 제공하는데 //더 간편하게 제공하는 것을 syntactic sugar //프로토 타입을 베이스트로한 살짝 덭붙여진 것 //async &amp; await //clear style of ...
  • 웹지기 02-27 3272 0 0 댓글 0
  • 60 [ javascript ] promise
  • 'use strict' //promse 코드를 이용해서 비동기식으로 처리 하는 방법 //Promse is a JavaScript object for asynchronous operation. //state : pending(진행중) -&gt; fulfilled(성공적으로 종료) or rejected(파일을 찾을 수 없거나 문제가 생기면) //Producer(원하는 기능을 수행해서 해당데이터를 만듬) vs Consumer(해당 데이터를 소비) //1. Producer //...
  • 웹지기 02-21 3161 0 0 댓글 0
  • 59 [ javascript ] 콜백지옥 - callback
  • 'use strict' //JavaScript is synchronous. //Execute the code block by orger after hoisting. //hoisting: var, function declearation //1. 동기와 비동기 console.log('1'); //동기식 setTimeout(function(){ //비동기식 console.log('2');//브라우져에서 함수에 의해 대기했다가 실행(비동기 실행방법) },1000); // 여기서 f...
  • 웹지기 02-21 3300 0 0 댓글 0
  • 58 [ javascript ] json 사용법
  • JSON //simplest data interchange format. //lightweight text-abased structure. //easy to read. //key-value pairs. //used for serialization and transmission of data between the network the network the network connection. //independent programming language and platform. //J...
  • 웹지기 02-21 2934 0 0 댓글 0
  • 열람중 [ javascript ] 유용한 함수들 10가지
  • javascript 유용한 함수들 10가지 https://youtu.be/3CUjtKJ7PJg // Q1. make a string out of an array { const fruits = ['apple', 'banana', 'orange']; const result = fruits.join(); console.log(result); } // Q2. make an array out of a string { ...
  • 웹지기 02-15 3308 0 0 댓글 0
  • 55 [ javascript ] object 생성, 사용방법
  • 'use strict'; 객체(Objects) //one of the JavaScript's data types. //a collection of related data and/or functionality. //Nearly all objects in JavaScript are instances of Objets. //object = { key : value }; //오브젝트는 키와벨류의 집합체 //변수에 접근가능한 property 와 값의 집합 1. 변수에 넣은 변하지 않는 데...
  • 웹지기 02-14 1171 0 0 댓글 0
  • 54 [ javascript ] 클래스 정의 및 사용
  • 객체지향 프로그래밍(Object-oriendted programming) class: template object: instance of a class JavaScript classes - introduced in ES6 - syntactical sugar over prototype-based inheritance js파일 상단에 선언(오류체크) 'use strict'; 1. 클래스선언(Class declarations) class Person {...
  • 웹지기 02-11 1410 0 0 댓글 0
  • 53 [ javascript ] 함수의 또다른 기능
  • 함수의 또다른 기능 함수는 다른 변수처럼 사용된다. 변수에 값으로 할당 할 수 있다. 다른 함수에 인수로 전달 가능 다른 함수에 의해 반환될 수 있다. First-class function functions are treated like any other variable can be assigned as a value to variable can be passed as an argument to other functions. can be returned by another func...
  • 웹지기 02-11 1121 0 0 댓글 0
  • 52 [ javascript ] 함수 선언 , 사용법
  • 함수(Function) 프로그램을 구성하는 빌딩블럭 서브프로그램이라고도 불리며 여러번 재사용이 가능 한가지의 작업이나 값을 계산할 때 사용 -fundamental building block in the program -subprogram can be used multiple times -performs a task or calculates a value 1. 함수 정의(Function declaration) function 함수명(파라미터1, 파라미터2) {비지니스로직.......
  • 웹지기 02-11 1098 0 0 댓글 0
  • 50 [ javascript ] 자바스크립트 변수 선언( var, let, const 차이)
  • ※ 자바스크립트 변수 선언 - 변수(Variables)는 변하는 데이터(값)를 저장할 수 있는 메모리 공간. - 변수에 데이터 값은 한개만 저장되므로, 같은 변수를 두번 사용하게 되면 나중에 입력된 변수값으로 저장된다. - 변수의 첫글자에 사용할 수 있는 문자들은 $, _ (언더바), 영문자 만 사용가능 - 변수 선언시 'use strict'; 선언을 통해 오류를 보여주고 방지하자. 변수선언( var = function-scoped ) var 변수명; var 변수...
  • 웹지기 02-09 1900 0 0 댓글 0
  • 49 [ javascript ] 자바스크립트 코드 작성시 주의 사항
  • javascript 는 대문자와 소문자를 구분한다. 코드가 끝났으면 ; 을 통해서 라인이 끝났다고 표시를 해준다. 가독성을 위해 코드는 한줄씩 사용하는게 좋다. 문자형 데이터를 작성할 때는 " 와 ' 를 사용해서 한다. 중복될 때는 \를 사용해서 사용한다. 문자 사잉에 "와 " 겹치지 않게 사용해줘야 한다. document.write("동해물과 " 백수산이 " 마르고 닳도록 "); //오류구문 docume...
  • 웹지기 02-09 1156 0 0 댓글 0
게시물 검색

회원로그인

접속자집계

오늘
5,415
어제
5,809
최대
33,828
전체
8,103,194

그누보드5
Copyright © funyphp.com. All rights reserved.