When you do this:
for (var k in obj)
when obj is a string, it iterates each of the indexes of the string. So you end up getting a k index for each letter of the string.
If you log the values of k in your for loop, you will see 0, 1, etc..., one for each letter in the string.
You can see here:
function object(obj){
var theArray =[];
var i =0;
for (var k in obj){
// capture the value of k so we can see what it is doing
theArray[i] = k;
i++;
}
return theArray;
}
var car = new object("hello");
document.write(JSON.stringify(car));
I can't speak to the exact logic for why it does this. You'd ultimately have to ask someone who designed this aspect of Javascript. But, since you can index the various letters of a string by property index like this:
var str = "hello"
console.log(str[1]); // "e"
You could argue that "0", "1","2", etc... are properties of the string object so since the for loop is just iterating the properties, it should iterate those.
Edit
If you try these:
console.log(Object.getOwnPropertyNames("hello"));
console.log(Object.keys("hello"));
You will see that Javascript clearly thinks that the indexes "0", "1", "2", "3", "4", "5" are all properties on a string. Thus, for (var k in obj) will iterate them just like any other property.
new?