프론트엔드/Javascript 연습과제 해답

자바스크립트 문법 6 - 배열 (Array) 의 기본 해답

syleemomo 2022. 1. 14. 15:21
728x90

 

* 연습과제 1

const numbers = new Array(100).fill(0)

for(let i=1; i<numbers.length; i++){
    if(i % 3 === 2){
        numbers[i] = i + 1
    }
}

console.log(numbers)

 

* 연습과제 2

const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
const words = []

for(let i=0; i<alphabet.length; i++){
    if(i === 0){
        words[i] = alphabet[i]
    }else{
        words[i] = words[i-1] + alphabet[i]
    }
}

console.log(words)

 

* 연습과제 3

const numbers = []

for(let i=0; i<100; i++){
    numbers[i] = 3*(i+1)
}

console.log(numbers)

 

* 연습과제 4

const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

function pickRandomIndex(n){
    return Math.floor(Math.random()*n)
}
function randomStr(n){
    const w = new Array(n).fill('a')
    for(let i in w){
        w[i] = alphabet[pickRandomIndex(alphabet.length)]
    }
    return w
}

console.log(randomStr(3))
console.log(randomStr(5))
console.log(randomStr(7))

 

* 연습과제 5

const numbers = []

for (let i = 0; i < 100; i++) {
    numbers[i] = 3 * (i + 1)
}
for (let i = 0; i < 100; i++) {
    if (numbers[i] % 6 === 0) numbers[i] = null
}

console.log(numbers)

 

* 연습과제 6

const movies = [
    {title: 'Harry Potter', release: '2003-02-22'}, 
    {title: 'Indiana Jhones', release: '2009-01-09'}, 
    {title: 'Jurassic Park', release: '2007-04-13'},
    {title: 'Iron man', release: '2012-12-18'},
    {title: 'Spider man', release: '2017-03-07'}
]

const movies_copied = []

for(let index in movies){
    // 구현하기
    movies_copied[index] = {title: movies[index].title, release: movies[index].release}
}

movies[1].title = 'syleemomo'

console.log(movies)
console.log(movies_copied)

 

* 연습과제 7

const words = [
    'abc',
    'animal',
    'fruit',
    'abba',
    'abcba',
    'location',
    'radar',
    'madam',
    'mario',
    'level'
]

function isPalindrome(word) {
    let isRight = true
    for (let i = 0; i < word.length / 2 - 1; i++) {
        if (word[i] === word[word.length - 1 - i]) {
            continue
        } else {
            return false
        }
    }
    return isRight
}

let cnt = 0
for (let word of words) {
    if (isPalindrome(word)) cnt++
}

console.log(cnt)

 

 

728x90