Search code examples
javascripthtmlarraystokenize

Can someone tell me why this is displaying numbers instead of characters?


Here is the code:

<!DOCTYPE html>
<html>
<head>
<style>
p {
    visibility: hidden;
}
</style>
</head>
<body>

<pre>Click the button to display the array values after the split.</pre>

<button onclick="myFunction(this)">Try it</button>

<p id="test">"ふ と、目が覚めると 部屋の 中は暗 か"</p>

<script>
function myFunction(p) {
    var str = document.getElementById("test").innerHTML;
    var array = [];
    var array2 = [];
    array.push(str.split(""));
    for (x = 0; x <= str.length; x++) {
        if (array[x] != " ") {
            array2.push(x);
        }
    }
    document.write(array2.toString());
}
</script>

</body>
</html>

I feel like the question is stated well but I have to put more content to post this question. So that is the reason for this bottom part. Sorry.


Solution

  • You are pushing your loop parameter x into the second array, not the character from the first array. You should change the code to:

    array2.push(array[x]);
    

    if your intention is to remove the spaces from the first string.