简体   繁体   中英

Access Object by dynamic key undefined error

I have a dictionary-like Object in Javascript and when I want to access to the dict by a key generated from page, the result is undefined :

How can I access the value correctly?

 var dict = { "red": "yes", "blue": "no" }; $("#trigger").click(function(){ alert(dict[$(this).text()]); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="trigger"> blue </div> 

There are blank spaces in the text. Use trim() to remove them

 var dict = { "red": "yes", "blue": "no" }; $("#trigger").click(function() { alert(dict[$(this).text().trim()]); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="trigger"> blue </div> 

It's because of extra spaces, use trim() to handle it

 var dict = { "red": "yes", "blue": "no" }; $("#trigger").click(function(){ alert(dict[$(this).text().trim()]); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="trigger"> blue </div> 

its have some extra space. use with trim() . it will reduce the spaces

 var dict = { "red": "yes", "blue": "no" }; $("#trigger").click(function() { console.log(dict[$(this).text().trim()]) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="trigger">blue</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM