rhanziy

javascript. Array배열1 본문

Html_css_js

javascript. Array배열1

rhanziy 2022. 1. 21. 15:50
const toBuy = ["potato", "tomato", "pizza"]; // list는 []

console.log(toBuy);
console.log(toBuy.length);
toBuy[3] = "olive"; // 배열의 개수를 알때, index는 0,1,2. . . 순서다.
console.log(toBuy);
toBuy.push("cheeze");  // 배열의 마지막에 값을 넣을때!
console.log(toBuy);

 

 

'use strict';

// Array 🎉🎉

// 1. Declaration
const arr1 = new Array();
const arr2 = [1, 2];

// 2. Index position
const fruits = [ '🍎', '🍌' ];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[fruits.length -1]); // 마지막 배열의 값을 가져오지!

// 3. Looping over an array
// print all fruits
// a. for
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// b. for of
console.clear( );
for ( let fruit of fruits ){ 
    console.log(fruit);
}

// c. forEach
fruits.forEach(function(fruit, index){
    console.log(fruit, index);
});

fruits.forEach((fruit) => console.log(fruit));

// 4. Addition, deletion,copy
// push: add an item to the end
fruits.push('🍙', '🍿');
console.log(fruits);
// pop: remove an item from the end!
fruits.pop( );
fruits.pop( );
console.log(fruits);

// unshift: add an item to the begining
fruits.unshift('🍕', '🍟');
console.log(fruits);
// shift: remove an item from the begining
fruits.shift( );
fruits.shift( );
console.log(fruits);
// note!! shift,  unshift are slower than pop, push

fruits.push('🍕','🍔','🍟');
console.log(fruits);
fruits.splice(1, 1, '🌭', '🧂'); // 1부터 1번째 배열 지우고 삽입
//  fruits.splice(1, 0, '🌭', '🧂'); 지우지않고 원하는 부분에 삽입가능
console.log(fruits);
// combine two arrays
const fruits2 = ['🥞', '🥐'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

// 5. Searching
//find the index
console.clear();
console.log(fruits);

console.log(fruits.indexOf('🍕')); //  배열의 몇번째에 있나. 없으면 -1
console.log(fruits.includes('🥪')); // 배열에 포함되어있나 boolean타입으로

// lastIndexOf
fruits.push('🍎');
console.log(fruits);
console.log(fruits.indexOf('🍎')); // 배열의 앞쪽에서부터
console.log(fruits.lastIndexOf('🍎')); // 배열의 뒤쪽에서부터

'Html_css_js' 카테고리의 다른 글

javascript. Promise  (0) 2022.01.28
javascript. Array배열2(filter, map, reduce, ...)  (0) 2022.01.23
javascript. Object객체  (0) 2022.01.21
css. 미디어쿼리 분기점  (0) 2022.01.20
javascript. class  (0) 2022.01.19
Comments