Web/Javascript

javascript list 예제

selfstarter 2019. 10. 29. 15:11

javascript list 예제

  • 배열 생성 시 new Array()를 하거나 []로 초기화

  • 배열에 요소 추가 함수 : push(obj)

  • 배열의 for문 : forEach, item은 해당 배열에 들어있는 값(인덱스x)

  • 배열 요소 가져오기 : splice(가져올 인덱스, 가져올 요소 개수)

  • 배열 요소 값 변경 : find로 요소의 값을 비교 후 해당하는 obj 반환하면 값 변경

  • 배열 요소 값 삭제 : find로 찾은 요소를 indexOf로 몇번째 위치하는지 찾은 후 splice로 해당 요소만 선택하면 삭제됨

          // 배열 선언
          test = []
    
          // 추가
          test.push({"name":1, "id":2});
          test.push({"name":2, "id":3});
          test.push({"name":3, "id":4});
          test.push({"name":4, "id":5});
    
          // Object 추가
          var obj = new Object()
          obj.name = 5;
          obj.id = 6;
          test.push(obj);
    
          test.forEach(function(item) {
              console.log(item.name + ", "+ item.id);
          });
    
          // slice 시작할 index, slice로 가져올 오브젝트 갯수
          console.log('==0,1 인덱스 값 가져오기');
          test.splice(0,2).forEach(function(item) {
              console.log(item.name + ", "+ item.id);
          });
    
          console.log('==0,1 인덱스 사라지고 남은 값만 test에 남음==');
          test.forEach(function(item) {
              console.log(item.name + ", "+ item.id);
          });
    
          // 값 변경
          console.log('==이름이 4인 object의 name 변경==');
          var test3 = test.find(function(item){
              return item.name == '4';
          });
          test3.name = '변경!!!';
          test.forEach(function(item) {
              console.log(item.name + ", "+ item.id);
          });
    
          // 값 삭제
          console.log('==이름이 변경!!!인 object 삭제==');
          var index = test.indexOf(test3)
          test.splice(index, 1);
          test.forEach(function(item) {
              console.log(item.name + ", "+ item.id);
          });
      });