조건문 If, 문자열

수툴리 양·2021년 5월 12일
0
post-thumbnail

Boot Camp day 03

1. If문

가장 지엽적인? 조건을 최상위로 올린다 (조건들의 교집합에서 바깥쪽 방향으로)
** 그리고 잊지마라 If문은 function 이다!

조건의 중첩과 여집합

※ 주의 ※
⚠️ 큰 조건 하에 하위 조건문 걸기 (연습 필요)
⚠️ 조건에 집중하다 조건 그물망에 걸리지 않는 여집합 (complement set) 놓치지 않기!

예를 들어,
A. 두 가지 조건을 모두 만족하는지 여부(Boolean)를 return하는 중첩 if문
B.
C. 세 가지 숫자 데이터를 비교하여 가장 작은 수를 return하는 조건문,
변수를 재할당 하여 출력하도록 짜보기
✮ if문에 else if와 else 가 반드시 따라와야하는 건 아님,

예제 A) ①문자열 word1, word2 의 길이가 홀수이고, ②두 문자열의 길이 모두 8보다 작은지 여부를 리턴하는 함수를 선언하라.

function checklong(word1, word2) {
  let a = word1.length, 
      b = word2.length;
  if (a % 2 === 1 && b % 2 === 1) {
    if(a < 8 && b < 8) {
      return true;
      }
    return false;
    }
  return false;
  }

예제 C) 문자열 데이터 3개를 받아와 가장 짧은 길이의 문자열을 출력하는 함수 bringmeShortword를 선언하라

let wordA;
let wordB;
let wordC;
    
function bringmeShortword(wordA, wordB, wordC) {
  // *하나의 문자열을 가장 짧은 단어로 가정(?)해서 할당
  let shortWord = wordA; // 새로운 변수를 선언 및 할당
  // 우선 가장 짧은 단어로 할당한 문자열을 다른 하나와 비교
  if (wordB.length < shortWord.length) {
    // 가장 짧다고 가정한 wordA보다 짧다는 wordB를 shortWord에 재할당
    shortWord = wordB; // * let은 다시 쓰지 않는다,
    // 그럼 이 조건에 걸려서 내려왔다면 나머지 하나와 비교해야 함
    }
    if (wordC.length < shortWord.length) {
      shortWord = wordC; // 이 조건에도 걸린다면 wordC가 가장 짧다고 판단됨(다음 comment이어-)
    // 근데 가장 첫번째(가장 바깥)의 조건에서 제외된다면? 
    //  처음에 임의로 할당한 wordA는 shortWord가 아니게되며,
    // 그럼 다시 나머지 다른 하나와 비교해야 함
    // wordA.length < wordB.length, 그럼 wordA와 wordC를 비교해야 함.(가장 짧은 문자열을 찾는 과정 중 이 조건은 최후의 보루(?)이므로)
  // shortWord = wordA; // 할당된 변수의 내용이 바뀌지 않음
  }
  else {
  if (wordC.length < shortWord.length) {
    shortWord = wordC;
    }
  }
  return shortWord;
  }
      

2개의 if문 병렬되었고(하나는 else if인 셈이라 봐도 되는지? 다른지?)
else로 빠져서 그 안에 조건을 한번 더 걸어서 여집합을 빠트리지 않았다!

💭 if & else 와 지시자return
함수는 위에서 아래로 순차적으로 내용을 실행한다,
if, else(if) 로 조건에 걸리는 한 경우에만 return하고 싶다거나 (그럼 한번만 return하는 것이고,)
조건을 하나만 걸어도 문제없을 시에는 else없이 바로 return해도 괜찮다.(두 번이상 return 가능한 것이다.)


tip 💡

함수 또는 If문 중첩 시, 간결한 코드 작성을 위해,
✮ 코드 내에서 새로운 변수를 선언 및 할당하는 연습하기


2. 문자열

Property 와 Method

(1) 속성 Property

  • 번역어(한국어)로 컴퓨터 언어를 습득하는 데엔 상당히 혼란을 줄 여지가 많다, 하지만 나의 언어로 포인트만 정리 및 표현하자면 'hold'가 가장 와닿는 듯.
    *attribute는 또 다른 개념에 포함되는 얘기였던 것 같은데 (리서치 필요)

🙄 What are the properties in JavaScript ?
Properties are the values associated with a JavaScript object.
Properties can usually be changed, added, and deleted, but some are read only.
The syntax for accessing the property of an object is:
i. e.) ObjectName.property /
ObjectName["property"]/
ObjectName[expression]
→ person.age /
person["age"] /
x = "age", person[x]

person = [name = 'sootulli', age = 22]

A JavaScript property is a characteristic of an object, often describing attributes associated with a data structure.

There are two kinds of properties: (1) Instance properties hold data that are specific to a given object instance.
(2) Static properties hold data that are shared among all object instances.

A property has a name (a string) and a value (primitive, method, or object reference).
"a property holds an object (reference)"
This distinction matters because the original referenced object remains unchanged when you change the property's value.

/출처/
MDN
w3school

(2) 메소드 method

  • 한마디 정의, 메소드는 function 이다. function은 뭐다? '작은 기능의 단위'이다!

A method is a function which is a property of an object. There are two kind of methods: Instance Methods which are built-in tasks performed by an object instance, or Static Methods which are tasks that are called directly on an object constructor.
i.g.) str.length, str.indexOf, ... , Math.floor

☀︎ Math라는 객체의 메소드

str.slice[index1, index2, ...], str.substring[index1, index2, ...]

☀︎ slice가 범용적, 배열에도 사용 가능

Note: In JavaScript functions themselves are objects, so, in that context, a method is actually an object reference to a function.
함수는 오브젝트의 속성이 될 수도 있음 즉, 함수 오브젝트의 레퍼런스가 메소드인 셈
*오브젝트는 숫자, 문자열 등등의 데이터 타입뿐만 아니라 함수도 받을 수 있음을,


👩🏻‍💻
굳이굳이 번역어로 생각해본다. 나도 아직 머리에서 영어로 생각하기는 .. 여간 부족 😴
아직은 babyEntry 레벨이기에, 본질적인 개념을 스스로 사고해보는 중
난 수학의 정석도 이렇게 안 했다.
🤓


| 퀴즈 | 71% (5/7 정답)
 실수인 셈이긴 하나
 매우 주의해야할 지점에서 틀림
  1. 결과값을 변수에 바로(한 줄로) 재할당
  2. 함수 선언 시(함수 body내에서) 매개변수에 임의로 다른 값을 할당 지양
profile
developer; not kim but Young

0개의 댓글