Basic JavaScript Question:
Download Job Interview Questions and Answers PDF
How to use strings as array indexes using JavaScript?
Answer:
JavaScript does not have a true hashtable object, but through its wierdness, you can use the array as a hashtable.
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
for(var i=0; i < days.length; i++) {
days[days[i]] = days[i];
}
document.write("days["Monday"]:"+days["Monday"]);
</script>
This produces
days["Monday"]:Monday
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
for(var i=0; i < days.length; i++) {
days[days[i]] = days[i];
}
document.write("days["Monday"]:"+days["Monday"]);
</script>
This produces
days["Monday"]:Monday
Download JavaScript Interview Questions And Answers
PDF
Previous Question | Next Question |
How to delete an array entry using JavaScript? | How to use "join()" to create a string from an array using JavaScript? |