且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将php代码转换为javascript代码

更新时间:2023-02-16 22:15:49

我认为你的代码在js中因为$ array而不正确。至于js,当一个数组被传输时,它只复制数组的地址,而不是整个状态。对于状态,我的意思是数组中的当前位置,这在您的代码中是必需的。所以每次函数makeArbo在js'部分运行时,数组总是以其位置的第一个元素开始,这不是你所期望的。

解决方案只是将数组移到函数外部,让它成为一个全局变量,一切都会好的。

---------------------------------刚开始在这里阅读----------- ------------------------

---------------------------------Just begin reading here-----------------------------------

1 Javascript不提供关联数组,您需要使用对象。参见

1 Javascript don't provide associative arrays, you need to use an object instead. See

function myVar(id, name, idParent){
          this.id = id;
          this.name = name;
          this.idParent = idParent;
}

2在Javascript中,itselt之前没有var的变量是全局变量。参见

2 In Javascript, a variable without a var before itselt is a global variable. See

array = new Array(...

3相应地更换您的其他代码。以下代码在我自己的服务器中作为html文件进行测试。

3 Replacing your other codes accordingly. The code below is tested in my own server as an html file.

4另外你应该处理返回值。使用一个对象来保存返回值,否则我们无法得到我们想要的东西。最后这一切一切正常,我可以去我的床...

4 Also, you should take care of the return value. Use an object to hold the return value or we can't get what we want. Finally everything works fine this time and I can go to my bed...

干杯!!

我的html文件:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p id="demo">My First Paragraph</p>

<script>

function myVar(id, name, idParent){
      this.id = id;
      this.name = name;
      this.idParent = idParent;
}

array = new Array(
    new myVar(1, "maths", 0),
    new myVar(2, "Topologie", 1),
    new myVar(3, "Algèbre", 1),
    new myVar(4, "Algèbre linéaire", 3),
    new myVar(5, "Arithmétique", 3),
    new myVar(6, "Thérorème de Bézout", 5),
    new myVar(7, "Informatique", 0),
    new myVar(8, "C-C++", 7),
    new myVar(9, "Les pointeurs", 8)
);

function run() {
    var result = {};//the object to hold the values' position
    result.value = "";//the real values;
    document.getElementById("demo").innerHTML = makeArbo(0, 0, -1, result).value;
}


function makeArbo(currentParent , currLevel, prevLevel, result)
{
    if (array.length >0)
    {
       for (var i = 0 ; i < array.length; i++)
       {
           if (currentParent == array[i].idParent)
           {        
               if (currLevel > prevLevel)
                   result.value += '<ul>';

               if (currLevel == prevLevel)   
                   result.value += '</li>';

               result.value += '<li>' + array[i].name + '</li>';

               if (currLevel > prevLevel)
                   prevLevel = currLevel;

               currLevel++;

               makeArbo(array[i].id, currLevel, prevLevel, result);

               currLevel--;
          }   
     }    
     if (currLevel == prevLevel) 
         result.value += '</li></ul>';

     return result;
}

}

window.onload = run;
</script>

</body>
</html>