logo

사전을 생성하고 키-값 쌍을 동적으로 추가하는 방법은 무엇입니까?

이 기사에서는 객체를 사용하여 키-값 쌍을 저장함으로써 JavaScript에서 사전을 만드는 방법을 설명합니다. JavaScript에는 사전 유형이 내장되어 있지 않지만 JavaScript 개체를 사용하여 효과적으로 사전 유형을 만들 수 있습니다. 사전 역할을 할 새로운 JavaScript 객체를 생성하는 것부터 시작해 보겠습니다.

통사론:



키는 문자열, 정수일 수 있습니다. key1 또는 임의의 숫자를 쓰면 문자열로 처리됩니다.

var dict = { key1 : value1 , key2 : value2 , .... };>
  • 빈 사전 만들기
    var dict = {};>
  • 사전에 키-값 쌍 추가
    dict[new_key] = new_value;>
    또는 new_key가 사전에 이미 존재하는 경우 이 값은 new_value로 업데이트됩니다.
    dict.new_key = new_value;>
  • 키-값 쌍에 액세스
    var value = dict[key];>
    또는
    var value = dict.key;>
  • 전체 사전 반복
    for(var key in dict) { console.log(key + ' : ' + dict[key]); }>

예:

HTML
   자바스크립트 사전제목> 머리> <body style='text-align: center;'> <h1 style='color: green;'>techcodeview.com h1><p>var 사전 = { <br />'괴짜' : 1 , <br />'대상': '2', <br />'괴짜': 3.5 <br />}; <br />피> <button onClick='fun()'>새 키-값 쌍 추가 버튼><p id='demo'>피><script>function fun() { var dict = { geek: 1, for: '2', geeks: 3.5, };  dict.new_geeks = 'new_value';  dict['another_new_geeks'] = 'another_value';  var to_show = 'var dict = { ';  for (dict의 var 키) { to_show += ''' + key + '' : ' + dict[key] + ' ';  } to_show += ' }; ';  document.getElementById('demo') .innerHTML = to_show;  } 스크립트> 본문> html>></pre> </code> <p dir='ltr'>  <b>  <strong>산출:</strong>  </b>  </p> <br /> <div id="container-4ae8242bd8e42d94c5c0bf390d5144e6"></div><br />  <img src='//techcodeview.com/img/javascript-misc/88/how-create-dictionary.webp' alt="">  <br></article>
                         
                        </div><!--//content-->
                    </div><!--//section-inner-->                 
                </section><!--//section-->
    
            </div><!--//primary-->
            <div class="secondary col-md-4 col-sm-12 col-xs-12">
                  <aside class="info aside section">
                    <div class="section-inner">
                        <h2 class="">범주</h2>
                        <div class="content">
                            <ul class="list-unstyled">
                                <li> <a href="/ds-tutorial/">Ds 튜토리얼</a> </li><li> <a href="/java-control-flow/">Java 제어 흐름</a> </li><li> <a href="/groovy-tutorial/">그루비 튜토리얼</a> </li><li> <a href="/python-collections-module/">Python 컬렉션 모듈</a> </li><li> <a href="/javascript-date/">자바스크립트 날짜</a> </li><li> <a href="/node-js-fs-module/">Node.js-Fs-모듈</a> </li><li> <a href="/combinatorial/">조합</a> </li><li> <a href="/order-statistics/">주문통계</a> </li><li> <a href="/python-string-programs/">Python 문자열 프로그램</a> </li><li> <a href="/python-pandas-dataframe-methods/">Python 팬더-Dataframe-메소드</a> </li>
                                
                            </ul>
                        </div><!--//content-->  
                    </div><!--//section-inner-->                 
                </aside><!--//aside-->
                
                 <aside class="testimonials aside section">
                   <div class="section-inner">
                        <h2 class="heading">DBMS(데이터베이스 관리 시스템) 도입 – Set 1</h2>
                        <div class="content">
                            <div class="item">
                                 <blockquote class="quote">                                  
                                    <span> <i class="fa fa-quote-left"></i> 괴짜를 위한 컴퓨터 공학 포털입니다. 여기에는 잘 쓰여지고, 잘 생각되고, 잘 설명된 컴퓨터 과학 및 프로그래밍 기사, 퀴즈 및 연습/경쟁 프로그래밍/회사 인터뷰 질문이 포함되어 있습니다.</span>
                                </blockquote>                
                                                                                             
                            </div><!--//item-->
                            
                            <p> <a class="more-link" href="/introduction-dbms-set-1"> <i class="fa fa-external-link"></i> 자세히보기</a> </p> 
                            
                        </div><!--//content-->
                    </div><!--//section-inner-->
                </aside><!--//section-->
                
               
                            
                 <aside class="languages aside section">
                    <div class="section-inner">
                        <h2 class="heading">재미있는 기사</h2>
                        <div class="content">
                            <ul class="list-unstyled">
                                <li class="item">
                                    <span class="title"> <strong> <a href="/bayes-theorem">베이즈 정리</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/tree/">나무</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/how-smooth-edges-photoshop">Photoshop에서 가장자리를 부드럽게 만드는 방법</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/joe-biden-net-worth-2024">조 바이든 순자산 2024 (미국 대통령 순자산)</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/program-factorial-number">숫자의 계승을 위한 프로그램</a> </strong> </span>
                                    
                                </li><!--//item-->
                               
                            </ul>
                        </div><!--//content-->
                    </div><!--//section-inner-->
                </aside><!--//section-->
                
              
                 <aside class="list music aside section">
                    <div class="section-inner">
                        <h2 class="heading">인기 게시물</h2>
                        <div class="content">
                            <ul class="list"> <li><a href="/matrix-multiplication-c">C의 행렬 곱셈</a>
</li><li><a href="/how-call-javascript-function-html">HTML에서 js 함수 호출</a>
</li><li><a href="/er-diagram-dbms">엔터티 관계형</a>
</li><li><a href="/uninstall-reinstall-angular-cli">각도 cli 제거</a>
</li><li><a href="/dynamic-array-java">자바의 동적 배열</a>
</li> 
                                
                                
                            </ul>
                        </div><!--//content-->
                    </div><!--//section-inner-->
                </aside><!--//section-->
              
            </div><!--//secondary-->    
        </div><!--//row-->
    </div><!--//masonry-->
    
	    <footer class="footer">
        <div class="container text-center">
                <span>
Copyright ©2025 판권 소유 |  <a href="//hu.techcodeview.com/">techcodeview.com</a> | <a href="/disclaimer" rel="nofollow noopener noreferrer" target="_blank">부인 성명</a>  |  <a href="/about-us" rel="nofollow noopener noreferrer" target="_blank">회사 소개</a>  |  <a href="/privacy-policy" rel="nofollow noopener noreferrer" target="_blank">개인 정보 보호 정책</a>  </span>
        </div>
    </footer>
 
         
    <script type="text/javascript" src="https://techcodeview.com/template/assets/plugins/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="https://techcodeview.com/template/assets/plugins/bootstrap/js/bootstrap.min.js"></script>    
    

    <script type="text/javascript" src="https://techcodeview.com/template/assets/js/main.js"></script>     
	
	<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script>
	
</body>
</html>