javascript数组返回[object Window]而不是数组内容

时间:2015-09-15 20:56:20

标签: javascript php arrays

我有问题。我写了一些回复"var pixelArray = [];"的PHP代码。之后,它回应了一些像这样的变量:"var canvas$id = 'can' + $id;"。并且还为每个变量回显"pixelArray.push(canvas$id);"

现在由于某种原因,当我运行脚本时,该数组不包含任何内容。

任何人都可以向我解释原因吗?

如果您需要更多信息,请告诉我。

编辑:

这是我的完整(但仍然简单)代码:

<?php
        $blockCounter = 1;
        $scriptCounter = 1;
        $arrayCounter = 1;
        $size = 32 * 32;
        $yLine = 1;
        while ($blockCounter <= $size)
        {

            if ($blockCounter == 32 * $yLine){
                echo "<canvas id=\"can$blockCounter\" width=\"17\" height=\"17\" style='border:1px solid #777777;'>GET A NEW BROWSER</canvas>";
                echo "<br>";
                $blockCounter = $blockCounter + 1;
                $yLine = $yLine + 1;
            }
            else{
                echo "<canvas id=\"can$blockCounter\" width=\"17\" height=\"17\" style='border:1px solid #777777;'>GET A NEW BROWSER</canvas>";
                $blockCounter = $blockCounter + 1;
            }

        }
        echo "<script>";
        echo "var pixelArray = [];";
        while ($arrayCounter <= $size)
        {
            echo "var name$arrayCounter = 'can' + $arrayCounter;";
            echo "pixelArray.push(name$arrayCounter);";
            $arrayCounter = $arrayCounter + 1;
        }
        while ($scriptCounter <= $size)
        {
            echo "var c = document.getElementById(\"can$scriptCounter\");";
            echo "picoco$scriptCounter = c.style.backgroundColor = \"#000000\";";
            $scriptCounter = $scriptCounter + 1;
        }
        echo "document.getElementById(\"arrayLoc\").innerHTML = pixelArray[0];";
        echo "</script>";
    ?> 
    <p id="arrayLoc"></p>

1 个答案:

答案 0 :(得分:2)

document.getElementById(“arrayLoc”)返回null,而不是pixelArray [0]。问题是在javascript加载时段落标记尚未加载到DOM中。您可以将它放在下面显示的脚本之上。

>>> import sys
>>> sys.setrecursionlimit(3)
>>> class Test:
...     def cycle(self, n=float("inf"), block="x"):
...         try:
...             return self.cycle(n-1, block)
...         except RuntimeError as e:
...             if str(e) == "maximum recursion depth exceeded":
...                 print("... forever")
...                 return 10
...
>>> t = Test()
>>> print(t.cycle())
... forever
10

或者在DOM加载后运行javascript。

    echo '<p id="arrayLoc"></p>';
    echo "<script>"
    echo "var pixelArray = [];";
    while ($arrayCounter <= $size)
    {
        echo "var name$arrayCounter = 'can' + $arrayCounter;";
        echo "pixelArray.push(name$arrayCounter);";
        $arrayCounter = $arrayCounter + 1;
    }
    while ($scriptCounter <= $size)
    {
        echo "var c = document.getElementById(\"can$scriptCounter\");";
        echo "picoco$scriptCounter = c.style.backgroundColor = \"#000000\";";
        $scriptCounter = $scriptCounter + 1;
    }
    echo "document.getElementById(\"arrayLoc\").innerHTML = pixelArray[0];";
    echo "</script>";
?>