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="/commerce-difference-between/">상업-차이점</a> </li><li> <a href="/python-requests/">Python 요청</a> </li><li> <a href="/exponents-maq/">지수 - Maq</a> </li><li> <a href="/java-networking/">자바 네트워킹</a> </li><li> <a href="/listicles/">목록</a> </li><li> <a href="/commerce-types/">상업 유형</a> </li><li> <a href="/json/">Json</a> </li><li> <a href="/money-banking/">돈과 은행</a> </li><li> <a href="/discrete-mathematics/">이산 수학</a> </li><li> <a href="/randomized/">무작위로</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">Java의 카운터 변수</h2>
                        <div class="content">
                            <div class="item">
                                 <blockquote class="quote">                                  
                                    <span> <i class="fa fa-quote-left"></i> Java 튜토리얼, 기능, 기록, 변수, 개체, 프로그램, 연산자, 죄송합니다 개념, 배열, 문자열, 지도, 수학, 메서드, 예제 등이 포함된 Java의 카운터 변수입니다.</span>
                                </blockquote>                
                                                                                             
                            </div><!--//item-->
                            
                            <p> <a class="more-link" href="/counter-variable-java"> <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="/standard-equation-parabola">포물선의 표준 방정식</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/what-is-an-acceptable-use-policy-24290">허용 가능한 사용 정책이란 무엇입니까?</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/what-is-nginx">NGINX란 무엇인가요?</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/math-pow-method-java-with-example">예제가 포함된 Java의 Math pow() 메소드</a> </strong> </span>
                                    
                                </li><!--//item--><li class="item">
                                    <span class="title"> <strong> <a href="/python-string-format-method">Python 문자열 형식() 메서드</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="/javabean">자바빈</a>
</li><li><a href="/method-overriding-java">Java의 메소드 재정의</a>
</li><li><a href="/list-religions">종교 목록</a>
</li><li><a href="/java-math-pow-method">math.pow 자바</a>
</li><li><a href="/how-many-zeros-1-million">0</a>
</li><li><a href="/operating-system-tutorial">운영 체제</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="//de.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>
	<script>
!function(){"use strict";let t=document.createElement("button");t.id="toTopBtn",t.innerHTML="↑";let e=`
        #toTopBtn {
            position: fixed;
            bottom: 25px;
            right: 25px;
            z-index: 9999;
            opacity: 0;
            visibility: hidden;
            background-color: #213141;
            color: white;
            border: none;
            border-radius: 8px;
            width: 50px;
            height: 50px;
            font-size: 24px;
            cursor: pointer;
            transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out;
        }
        #toTopBtn:hover {
            background-color: #555;
        }
    `,i=document.createElement("style");i.type="text/css",i.innerText=e,document.head.appendChild(i),document.body.appendChild(t),window.addEventListener("scroll",()=>{let e=window.scrollY||document.documentElement.scrollTop;e>300?(t.style.opacity="1",t.style.visibility="visible"):(t.style.opacity="0",t.style.visibility="hidden")}),t.addEventListener("click",()=>{window.scrollTo({top:0,behavior:"smooth"})})}();
</script>
</body>
</html>