나의 개발일지(김지헌)
배열 본문
변수 = []
변수[순서]
const arr = [1,2,3,4,5] //index 는 배열안에 자리 잡은 순서이다 0부터 시작한다.
// console.log(arr[0])// 호출한 배열을 부를때는 변수[순서] 해주면 된다.
// console.log(arr[1])
// console.log(arr[2])
// console.log(arr[3])
// console.log(arr[4])
console.log(arr.length) //길이는 1부터 시작한다
console.log(arr[arr.length-1]) //마지막요소를 부를때는 길이의 -1 해주면 된다.
배열 추가 및 삭제
배열 추가
const color = ['red', 'blue', 'yello']
console.log(color) //기존 값인 'red', 'blue', 'yello' 출력된다.
color.push('black')//push를 사용하여 color의 변수안에 black 을 추가한다.
console.log(color)//black 이 추가되어 'red', 'blue', 'yello', 'black' 출력된다.
배열 삭제
color.pop('black')// black 을 제거
console.log(color)// black 이 제거되어 'red', 'blue', 'yello'이 나온다.
배열과 반복문
const color = ['red', 'blue', 'yello']
for (i = 0; i < color.length; i++){//color의 길이보다 작게 반복한다.
console.log(color[i]) //red blue yello 순차적으로 나온다
}
for (i = 0; i < color.length; i++){//color의 길이보다 작게 반복한다.
console.log(color[i]) //red blue yello 순차적으로 나온다
}
const color = ['red', 'blue', 'yello']
for (const colors of color){ //colors 변수안에 color의 변수에 접근하여 데이터를 colors에 넣어준다
console.log(colors)
}
for (const colors of color){ //colors 변수안에 color의 변수에 접근하여 데이터를 colors에 넣어준다
console.log(colors)
}
const data = [1,2,3,4,5,6,7,8,9,10]
1.
let sum = 0; //반복 했던 sum의 값이 저장된다 55
for (i = 0; i < data.length; i++){
sum = sum + data[i]
}
console.log(sum)
const avg = sum / data.length
console.log(avg) // 5.5
2.
let sum = 0; // 55
for (const datas of data){
sum += datas //data안에 있는 데이터를 누적해서 넣어준다. += 누적한다는 뜻
}
console.log(sum)
const avg = sum / data.length
console.log(avg) // 5.5
let sum = 0; // 55
for (const datas of data){
sum += datas //data안에 있는 데이터를 누적해서 넣어준다. += 누적한다는 뜻
}
console.log(sum)
const avg = sum / data.length
console.log(avg) // 5.5
실행 해보면 두개의 결과 값이 같다는 걸 알 수 있는데 1번의 코드보다 2번의 코드가 좀더 간단하다는 걸 알 수있다.
'javascript 공부' 카테고리의 다른 글
함수 (0) | 2022.09.23 |
---|---|
조건문과 반복문 (0) | 2022.09.23 |
JAVASCRIPT (2) | 2022.09.23 |