How does for in js implement traversal in foreach
- 2020-03-30 03:09:04
- OfStack
Foreach is not a keyword in js, but it can be traversed using var v in array. But it's important to note that,
You get the key instead of the value. See the examples:
You get the key instead of the value. See the examples:
<script type="text/javascript">
//Regular array
var intArray = new Array();
intArray[0] = " The first one ";
intArray[1] = " The second ";
for(var i = 0; i<intArray.length;i++)
{
alert(intArray[i]); //The first one, the second one
}
//You get a subscript (like the key of a dictionary)
for(var key in intArray)
{
alert(key); // 0,1
}
//The dictionary array
var dicArray = new Array();
dicArray["f"] = " The first one ";
dicArray["s"] = " The second ";
//Unable to get to
for(var i = 0; i<dicArray.length;i++)
{
alert(dicArray[i]);
}
//I get a subscript
for(var key in dicArray)
{
alert(key); // f,s
}
</script>