const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong :( ');
}
}
};
let is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;
is2p2();
console.log(is2p2.name);
//Output: checkThatTwoPlusTwoEqualsFourAMillionTimes
- Array object에서만 사용가능한 method.
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
fruits.forEach(fruit => console.log(I want to eat a ${fruit}.
))
/Output:
I want to eat a mango.
I want to eat a papaya.
I want to eat a pineapple.
I want to eat a apple.
/
#### 2-2. The .map() Method
- 새로운 array 만듬.
```javascript
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];
const secretMessage =
animals.map(animal => animal[0]);
console.log(secretMessage.join(''));
//Output: HelloWorld
const bigNumbers = [100, 200, 300, 400, 500];
const smallNumbers = bigNumbers.map(number => number/100);
console.log(smallNumbers);
//Output: [ 1, 2, 3, 4, 5 ]
- .join() method
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// expected output: "Fire,Air,Water"console.log(elements.join(''));
// expected output: "FireAirWater"console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
const randomNumbers = [375, 200, 3.14, 7, 13, 852];
const smallNumbers =
randomNumbers.filter (number => {
if (number < 250){
return true;
}
});
console.log(smallNumbers);
//or
const smallNumbers =
randomNumbers.filter (number => {
return number < 250;
});
console.log(smallNumbers);
//Output: [ 200, 3.14, 7, 13 ]
const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];
const longFavoriteWords = favoriteWords.filter (word => {
if (word.length > 7) {
return true;
}
});
console.log(longFavoriteWords);
//Output: [ 'nostalgia', 'hyperbole', 'esoteric' ]
array 안에서 특정 element의 위치를 찾을 때 사용
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
const foundAnimal = animals.findIndex(animal =>{
return animal.length === 8;});
console.log(foundAnimal);
//또는 밑의 함수로도 표현 가능함.
const foundAnimal = animals.findIndex(animal => {
return animal === 'elephant';});
//Output: 7
const startsWithS = animals.findIndex(animal => {
return animal[0] === 's' ? true : false;
});
//Ternary Operator 사용
//Output: 3
array의 elements를 통해 반복한 후 단일 값을 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;
});
console.log(newSum);
/*Output:
The value of accumulator: 1
The value of currentValue: 3
The value of accumulator: 4
The value of currentValue: 5
The value of accumulator: 9
The value of currentValue: 7
*/
const newSum =
newNumbers.reduce(
(accumulator, currentValue) => {
return accumulator + currentValue
}, 10);
console.log(newSum);
//Output: 26
Array 안의 모든 elements가 주어진 판별 함수를 통과하는지 테스트
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
const nums = [1, 50, 75, 200, 350, 525, 1000];
let numsOne = nums.every(num => num < 0);
console.log(numsOne);
//Output: false
elements를 추가할 때 쓰는 method
const chores = ['wash dishes', 'do laundry', 'take out trash'];
chores.push('clean the room', 'clean the toilet');
console.log(chores);
/*Output:
[ 'wash dishes',
'do laundry',
'take out trash',
'clean the room',
'clean the toilet' ]
*/
const chores = ['wash dishes', 'do laundry', 'take out trash', 'cook dinner', 'mop floor'];
chores.pop();
console.log(chores);
/*Output:
[ 'wash dishes', 'do laundry', 'take out trash', 'cook dinner' ]
*/
// 이 외에도 .join(), .slice(), .splice(), .shift(), .unshift(), and .concat()와 같은 여러 method 존재.
const groceryList =
['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];
groceryList.shift();
console.log(groceryList);
/*OutPut: [ 'bananas',
'coffee beans',
'brown rice',
'pasta',
'coconut oil',
'plantains' ]
*/
groceryList.unshift('popcorn');
console.log(groceryList);
/* Output:
[ 'popcorn',
'bananas',
'coffee beans',
'brown rice',
'pasta',
'coconut oil',
'plantains' ]
*/
console.log(groceryList.slice(1,4)); //또는
console.log(groceryList.slice(1,-3));
/*Output:
[ 'bananas', 'coffee beans', 'brown rice' ]
*/
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
**begin, end 인덱스 헷갈리지 않도록 주의!!
배열에서 지정된 elements를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않을 경우 -1을 반환.
const pastaIndex = groceryList.indexOf('pasta');
console.log(pastaIndex);
//Output: 4
//fromIndex를 옵션으로 선택할 수 있다.
console.log('pasta, 2));
//두번째 인자로 2가 주어지면 탐색의 대상이 2번째 index에서 시작한다. 단, index값은 변하지 않는다.