본문 바로가기
Programming/JavaScript

[CodeAcademy] Array, loop, Iterators

// 배열(Arrays)
const hobbies = ['a', 'b', 'c']
console.log(hobbies)

const famousSayings = ['Fortune favors the brave.', 'A joke is a very serious thing.', 'Where there is love there is life.'];
const listItem = famousSayings[0];
console.log(listItem);
console.log(famousSayings[2]);
console.log(famousSayings[3]);
// 음수 인덱싱은 arr.at(-1);  이런식으로 구현

let groceryList = ['bread', 'tomatoes', 'milk'];
groceryList[1] = 'avocados';
console.log(groceryList);

// 특이점: let으로 지정된 list 변수의 내용물 변경, 업데이트 가능
let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];

const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];

condiments[0] = "Mayo";
console.log(condiments);
condiments = ['Mayo'];
console.log(condiments);
utensils[3] = 'Spoon'
console.log(utensils)
utensils[4] = 'hello'
console.log(utensils)
// 단, 새 리스트의 새 element로 다시 정의하는 것은 불가능
utensils = ['newthing']

// len(변수)은 JS에서 변수.length 로 구할 수 있음
const objectives = ['Learn a new language', 'Read 52 books', 'Run a marathon'];
console.log(objectives.length)

// 리스트.extend(내용)은 배열.push(내용)으로 구현. JS는 여러개 한번에 가능
const chores1 = ['wash dishes', 'do laundry', 'take out trash'];
chores1.push('checking mails', 'etc');  // 파이썬 extend는 lst.extend(['c','d']) 이런식으로 써야 인식됨
console.log(chores1);

// pop()은 마지막 것 없애고 그 없앤 것을 담는다.
const chores = ['wash dishes', 'do laundry', 'take out trash', 'cook dinner', 'mop floor'];
const removed = chores.pop();
console.log(chores, '\n', removed); // 한 번에 여러개 줄바꿔서 출력하기

const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];
groceryList.shift() // 제일 앞의 것 제거
console.log(groceryList)
groceryList.unshift('popcorn') // 하나 이상 원소 제일 앞에 추가
console.log(groceryList)
console.log(groceryList.slice(1,4)) // [num:num] 개념, 마지막꺼 미포함
console.log(groceryList)

const pastaIndex = groceryList.indexOf('pasta') // 인덱스 번호 찾기
console.log(pastaIndex)

const concept = ['arrays', 'can', 'be', 'mutated'];
function changeArr(arr){
  arr[3] = 'MUTATED';
}
changeArr(concept);
console.log(concept);

const removeElement = newArr => {
  newArr.pop()
  };
removeElement(concept)
console.log(concept)

const numberClusters = [[1,2],[3,4],[5,6]];
const target = numberClusters[2][1]; // 리스트 인덱스 호출방식 동일
console.log(target);




// loop (반복, 순회)
for (let count = 5; count <= 10; count++) {
  console.log(count);
};   // count === 10; 은 10일때만 동작하라는 의미 -> 두번째는 범위 조건이여야 반복됨

for (let counter = 3; counter >= 0; counter--){
  console.log(counter);
}

const vacationSpots = ['Bali', 'Paris', 'Tulum'];
for (let i = 0; i < vacationSpots.length; i++) {
  console.log('I would love to visit ' + vacationSpots[i]);
};

const bobsFollowers = ['a', 'b', 'c', 'd'];
const tinasFollowers = ['c', 'd', 'e'];
let mutualFollowers = [];
for (let i = 0; i < bobsFollowers.length; i++) {
  for (let j = 0; j < tinasFollowers.length; j++) {
    if (bobsFollowers[i] === tinasFollowers[j]) {
      mutualFollowers.push(tinasFollowers[j]);
    };
  };
};
console.log(mutualFollowers);

const cards = ['diamond', 'spade', 'heart', 'club'];
let currentCard;
while (currentCard !== 'spade') {
  currentCard = cards[Math.floor(Math.random() * 4)];
  console.log(currentCard)
};
// do {} while(); : while 조건에 상관없이 초기 코드 실행 有
const cupsOfSugarNeeded = 3;
let cupsAdded = 0;
do {
cupsAdded += 1;
console.log(cupsAdded);
} while (cupsAdded < cupsOfSugarNeeded);

const rapperArray = ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"];
for (let i = 0; i < rapperArray.length; i++) {
  console.log(rapperArray[i]);
  if (rapperArray[i] === 'Notorious B.I.G.') {
    break;
  }
}
console.log("And if you don't know, now you know.");



// Higher order functions
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
};  // 매우 긴 이름을 지닌 함수를 동작은 유지하면서 이름만 간단하게 다시 재 정의할 수 있다.
const isTwoPlusTwo = checkThatTwoPlusTwoEqualsFourAMillionTimes;
isTwoPlusTwo();
console.log(isTwoPlusTwo.name); // 다만 원본 함수의 이름은 .name으로 다시 조회 가능 (object type으로 .length 등 적용가능)
console.log(isTwoPlusTwo.toString()); // toString() 적용시, 원본 함수의 코드 내부 조회가 그대로 가능

const addTwo = num => {
  return num + 2;
} // 함수 안에 함수 넣기 + 조건문 삼항연산자
const checkConsistentOutput = (func, val) => {
  const checkA = val + 2;
  const checkB = func(val);
  return checkA === checkB ? func(val) : 'inconsistent results';
}
console.log(checkConsistentOutput(addTwo, 5));



// Iterators: 모두 for문으로 가능하지만 좀 더 간단하게 구현 가능토록 함
const artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];
artists.forEach(artist => {
  console.log(artist + ' is one of my favorite artists.');
}); // 요소를 하나씩 꺼내서 실행만 함(새로 만드는 것이 아니므로 변수 선언처럼 정의하면 undefined됨)
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
fruits.forEach(fruits => {
  console.log("I want to eat a " + fruits);
});


const numbers = [1, 2, 3, 4, 5];
const squareNumbers = numbers.map(number => {
  return number * number;
}); // 요소를 하나씩 꺼내서 특정 규칙에 맞춰 변형하여 만듦
console.log(squareNumbers);

const animals1 = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];
const secretMessage = animals1.map(animal => animal[0]);
console.log(secretMessage.join(''));

const bigNumbers = [100, 200, 300, 400, 500];
const smallNumbers1 = bigNumbers.map(num => num / 100);
console.log(smallNumbers1);



const things = ['desk', 'chair', 5, 'backpack', 3.14, 100];
const onlyNumbers = things.filter(thing => {
  return typeof thing === 'number';   // typeof 대상 : 대상에 대한 type 검사 
}); // 조건에 맞는 필터링할 때 사용
console.log(onlyNumbers);

const randomNumbers = [375, 200, 3.14, 7, 13, 852];
const smallNumbers = randomNumbers.filter(num => num < 250);
console.log(smallNumbers);

const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];
const longFavoriteWords = favoriteWords.filter(word => word.length > 7);
console.log(longFavoriteWords);
// 아래처럼 합칠 수 있음
users
  .filter(user => user.active)
  .map(user => user.name);
// map, filter는 새로 만들어내므로 특정 변수에 대한 선언으로 시작 <-> forEach는 대상 리스트.forEach(변수 =>{})로 시작

// findIndex는 해당되는 것이 여러 개인 경우 가장 빨리 발견된 인덱스 하나만 도출한다.
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
const foundAnimal = animals.findIndex(animal => animal === 'elephant');
const startsWithS = animals.findIndex(animal => animal[0] === 's' );
console.log(foundAnimal, '\n' , startsWithS);

// .reduce((누적값 = 기본값은 첫 입력값, 현재값) => {return할 로직}, 누적 초기값 설정(생략시 첫 입력값으로 자동설정)); 
const newNumbers = [1, 3, 5, 7];
const newSum = newNumbers.reduce((accumulator, currentValue) => {
  console.log('The value of accumulator: ', accumulator);
  console.log('The value of currentValue: ', currentValue);
  return accumulator + currentValue;
}, 10);

console.log(newSum);

const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];
console.log(words.some((word) => word.length < 6)); // 대상에 조건이 하나라도 만족하는게 있는지 판별하기: 대상.some()
const interestingWords = words.filter(word => word.length > 5); 
console.log(interestingWords.every((word) => word.length > 5)); // 각 요소가 모두 조건을 만족하는지 판별하기: 대상.every()


const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];
const nums = [1, 50, 75, 200, 350, 525, 1000];

//  Choose a method that will return undefined
cities.forEach(city => console.log('Have you visited ' + city + '?'));
// Choose a method that will return a new array
const longCities = cities.filter(city => city.length > 7);
// Choose a method that will return a single value
const word = cities.reduce((acc, currVal) => {
  return acc + currVal[0]
}, "C");
console.log(word)
// Choose a method that will return a new array
const smallerNums = nums.map(num => num - 5);
// Choose a method that will return a boolean value
nums.some(num => num < 0);
nums.every(num => num < 0);

 

728x90
반응형