javascript ES6문법 다지기 (1)

유현영·2020년 2월 17일
1

javascript

목록 보기
1/2
post-thumbnail

인프런의 강의를 기반으로 ES6문법에 대한 정리를 해보겠다.
강의링크

ES6 (ECMAScript)란?

다양한 웹 브라우저에서 자바스크립트가 공통되게 잘 작동하기 위해서 표준규격
자바스트립트를 이루는 코어 스크립트 언어
􏰊􏰉

변수 선언방식 비교

var : ES6 업데이트 이전에 변수 할당방식 매우 자유롭게 사용이 가능하며 function scope

var name = "yyy";
console.log(name)
var name = "www";
console.log(name)

> yyy
  www

let : 변수에 재할당이 가능한 block scope

let hello='first hello';  
{
  let hello = 'inner hello';  
  console.log(hello); // inner hello
}
console.log(hello); // first hello

const : 변수 재선언, 재할당 모두 불가능한 block scope (배열과 오브젝트의 값을 변경하는 것은 가능함)

const hello='hello';
hello='change hello'; // 재정의 불가
----------------------------------------------
const hello='hello!';
{
  const hello='inner hello!'; 
  console.log(hello); // inner hello!
}
console.log(hello); // hello! 
//블록 단위 스코프이기 때문에 선언 가능

➡️ const를 기본으로 사용하고 변경이 될수 있는 것은 let을 사용하여 진행하는 방식으로 하자

ES2015에서 제공하는 새로운 메소드

  1. 같은 문자열인지 확인 하는 메소드
let str = "helloooo";
let matchstr = "hello

//시작값이 같은지
console.log(str.startsWith(matchstr)); 
//끝값이 같은지
console.log(str.endsWith(matchstr)); 
//매칭되는 문자열이 있는지
console.log(str.includes(matchstr)); 

Array

  1. 배열을 출력하는 방법
var data = [1,2,undefined,NaN,null,""];
//forEach로 출력
data.forEach(function(value) {
  console.log(value)
}
//for in으로 출력
for(let idx in data) {
  console.log(data[i])
}
// 문제 : 자기 자신이 가지고 있지 않은 상위의 값들도 돌면서 출력하는 문제가 있음

//for of로 출력
for(let value in data) {
  console.log(data[i])
}       
//배열만을 위한 반복문이 아니므로 문자열 순회도 가능
  1. spread operator (펼침연산자 ...)
  • Iterable Object(열거 가능한 오브젝트)를 하나씩 전개합니다. (참조를 끊고 메모리 새로운 공간에 카피)
  • 표현방식 : […iterable]
  • immutable array 즉, 배열을 바꾸지 않고 새로운 값을 복사할 수 있는 방법으로 배열을 합치거나 펼쳐지는 방식을 구현할때 유용
let pre = ["apple","orange",100]
let newData = [...pre];
console.log(pre)  //["apple","orange",100]
console.log(newData) //["apple","orange",100]
console.log(newData === pre) //false
  1. spread operator 활용
//1. 배열 합치기
let pre = [100,"hello",null];
let newDate = [0,10, ...pre, 4];

console.log(newData) 
// [0,10, 100,"hello",null, 4]

//2. 개별 파라미터로 값전달
function sum(a,b,c){
  return a+b+c
}
let arr = [100, 200, 300];
//spread operator 출현 이전의 방식
console.log(sum.apply(null, arr)) //600
//이후의 방식
console.log(sum(...arr))  //600
  1. from 메소드 (
  • argument는 객체의 형태로(배열아님) 가변적인 파라미터에 사용함
  • from 함수는 유사배열을 배열로 만들어 줌
//1. 기본적으로 출력하는 방법
function addMark() {
  let newData = [];
  for(let i=0; i <argument.length; i++) {
    newData.push(argument[i] + "!")
  }
  console.log(newData); //["1!","2!"] 
}
addMark(1,2)

//2. (배열메소드) map 사용하여 더 편하게 출력하기
function addMark() {
  let newArray = Array.from(arguments) //arguments로부터 배열을 만든다
  let newData arguments.map(function(value) {
      return value + "!";
  }
  console.log(newData); //["1!","2!"] 
}
addMark(1,2)

실습해보기

문제 : filter, include, from 메소드를 사용해서 문자열 e가 포함된 노드로 구성된 배열을 만들어서 반환하기

<body>
  <ul>
    <li>orange</li>
    <li>apple</li>
    <li>banana</li>
    <li>strawberry</li>
  </ul>

  </body>
function print() {
 
  let list = document.querySelectorAll("li")
  let listArray = Array.from(list)
 // let result = listArray.filter(fruit => fruit.includes('e'))
  let resultArray = listArray.filter(function(v) {
    return v.innerText.includes("e") //도메인에서 뽑아내는 innerText
  });
  console.log(resultArray.length);
  
}
print();
profile
오늘보다 더 나은 내일

1개의 댓글

comment-user-thumbnail
2021년 2월 15일

안녕하세요 자바스크립트 막 배우기 시작한 뉴비인데요,
요약 정리해주신 JS잘 보았습니다!
다름이 아니라 실습해보기에서 console.log(resultArray.length)를 치면 콘솔창에
3이 나와야 하는 것 아닌가요.. 아무것도 안 나와 질문드립니다!

답글 달기