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>  <img src='//techcodeview.com/img/javascript-misc/88/how-create-dictionary.webp' alt="">  <br></article><div class="rekl_placeholder"><script type="text/javascript">atOptions = {'key' : 'f2b09f3e7178b263531e10998e9a32fa','format' : 'iframe','height' : 250,'width' : 300,'params' : {}};</script><script type="text/javascript" src="//spiritscaution.com/f2b09f3e7178b263531e10998e9a32fa/invoke.js"></script></div> </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="/java-mail-tutorial/">자바 메일 튜토리얼</a> </li><li> <a href="/dynamic-programming/">동적 프로그래밍</a> </li><li> <a href="/cpp-control-flow/">Cpp 제어 흐름</a> </li><li> <a href="/ejb-tutorial/">Ejb 튜토리얼</a> </li><li> <a href="/splunk-tutorial/">스플렁크 튜토리얼</a> </li><li> <a href="/postgresql-tutorial/">Postgresql 튜토리얼</a> </li><li> <a href="/data-mining/">데이터 수집</a> </li><li> <a href="/android-tutorial/">안드로이드 튜토리얼</a> </li><li> <a href="/alphabet/">알파벳</a> </li><li> <a href="/quick-sort/">빠른 정렬</a> </li>
                                
                            </ul>
                        </div><!--//content-->  
                    </div><!--//section-inner-->                 
                </aside><!--//aside-->
                
                 <aside class="testimonials aside section">
                	 <div class="section-inner">
                        <div class="content">
                            <div class="item">
  								<div class="rekl_placeholder" id="sidebar_placeholder_1"> <script type="text/javascript">atOptions = {'key' : 'f53f1abf3c3a788f849c12a956865db1','format' : 'iframe','height' : 300,'width' : 160,'params' : {}};</script><script type="text/javascript" src="//spiritscaution.com/f53f1abf3c3a788f849c12a956865db1/invoke.js"></script> <br></div>                                                   
                            </div>
                        </div>
                    </div>
                   <div class="section-inner">
                        <h2 class="heading">Python 클래스의 자기</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="/self-python-class"> <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="/auc-roc-curve-machine-learning">기계 학습의 AUC ROC 곡선</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/learn-reactjs-tutorial">ReactJS 튜토리얼 알아보기</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/list-top-10-most-dangerous-countries-africa">아프리카에서 가장 위험한 상위 10개 국가 목록</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/web-scraping/">웹스크래핑</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/java-hashtable-class">Java 해시테이블 클래스</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="/sql-cast-function">캐스트 SQL</a>
</li><li><a href="/how-sort-arraylist-java">정렬 배열 목록 자바</a>
</li><li><a href="/how-download-youtube-video-vlc-media-player">VLC를 사용하여 YouTube 동영상 다운로드</a>
</li><li><a href="/what-is-10-50">50개 중 10개</a>
</li><li><a href="/java-convert-char-int">char에서 int로 변환 java</a>
</li><li><a href="/bfs-algorithm">bfs 검색</a>
</li><li><a href="/mysql-create-user">mysql 사용자 생성</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="//hr.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>