多维Javascript打开数组

时间:2014-12-24 07:00:20

标签: javascript arrays

我在分配和检索开放数组中元素的值时遇到困难,数组大小和维度不固定,因此在迭代期间由于扩展或缩小而导致。我将数组声明为var NODES[[]];,试图分配,检索值并获取数组中任何维度的长度结果错误的值。特别是使用var le = NODES[0].length ;代码,我希望看到第一维的总长度。

    var NODES =[[]]
    scene = editor.scene;
    scene.traverse( function(e) {

    if ( (e instanceof THREE.Line) && (e.name = 'main line' ) )
    {

        for (i=0; i<e.geometry.vertices.length; i++){

            var x = e.position.x+ e.geometry.vertices[i].x
            var y = e.position.y+ e.geometry.vertices[i].y
            var z = e.position.z+ e.geometry.vertices[i].z      

            NODES[node_cnt,0] = x;
            NODES[node_cnt,1] = y;
            NODES[node_cnt,2] = z;
            node_cnt++;
        }

     cnt++;      

    }; 
    var le = NODES[0].length ;


EXPECTED RESULT 
NODES[0][0] = 10; NODES[0][1] = 20;  NODES[0][3] = 30; 
NODES[1][0] = 40; NODES[1][1] = 50;  NODES[1][3] = 60; 
NODES[2][0] = 70; NODES[2][1] = 80;  NODES[2][3] = 90; 

with `var le = NODES[0].length ;` I expect to see 3 because I'm requesting the length of 1st dimension

1 个答案:

答案 0 :(得分:0)

这是多维数组的javascript解释,NODES是一个实际包含3个数组的数组,NODES中包含的每个数组都包含一个字符串:

    var NODES = [[],[],[]];

    for (var i = 0; i < 10 ; i++) {
        NODES[0].push(i + 'x');
        NODES[1].push(i + 'y');
        NODES[2].push(i + 'z');


    }
    console.log(NODES[0].lenght);

如果每个包含的数组都应包含另一个数组,则执行此操作的sintax应为:

    NODES[0].push([i + 'x']);

抱歉,我不清楚node_cntcnt是什么意思,但我认为你应该这样做:

var NODES =[[],[],[]]
    scene = editor.scene;
    scene.traverse( function(e) {

    if ( (e instanceof THREE.Line) && (e.name = 'main line' ) )
    {

        for (i=0; i<e.geometry.vertices.length; i++){

            var x = e.position.x+ e.geometry.vertices[i].x
            var y = e.position.y+ e.geometry.vertices[i].y
            var z = e.position.z+ e.geometry.vertices[i].z      

            NODES[0].push(x);
            NODES[1].push(y);
            NODES[2].push(z);
            node_cnt++;
        }

     cnt++;      

    }; 
    var le = NODES[0].length ;