js再帰的に一括的に配列に属性と値を追加することを実現する.

1208 ワード




    
    <script type="text/javascript">

        function iteration(data) {
            for (var j = 0; j < data.length; j++) {
                data[j].type = 1
                if (data[j].chiden != undefined && data[j].chiden.length > 0) {
                    iteration(data[j].chiden)
                }
            }
        }

        var data = new Array()
        data[0] = new Object();
        data[1] = new Object();
        data[1].name = "chiden1"
        data[1].chiden = new Array()
        data[1].chiden[0] = new Object();
        data[1].chiden[0].name = "chiden2"
        data[1].chiden[0].chiden = new Array()
        data[1].chiden[0].chiden[0] = new Object();
        data[1].chiden[0].chiden[0].name = "chiden3"
        data[1].chiden[0].chiden[0].chiden = new Array()
        data[2] = new Object();
        iteration(data)
        var newData = data
        console.log(newData);

    </script>



</code></pre> 
  <h2>            chiden      type=1</h2> 
 </div> 
</div>
                            </div>
                        </div>