JS使用两个数组

时间:2013-09-19 11:46:33

标签: javascript

我需要创建一个数组cells,如我的评论中所述。 我想知道这个脚本有什么问题,以及实现这个结果的更多性能方法。

查看js fiddle http://jsfiddle.net/XvTrf/5/

var data = ['D-0','D-1','D-2','D-3','D-4','D-5','D-6','D-7','D-8','D-9'];

var cells=[];
var d = 0, lenD = data.length;

while(d< lenD){
    if(d === 1 || d === 5 || d ===6){
       cells.push('test');
    }else {
        cells.push(data[d]);
    }
    d++;
}
console.log(cells);


/* result wanted
D-0
test
D-1
D-2
D-3
test
test
D-4
D-5
D-6
D-7
D-8
D-9

*/

1 个答案:

答案 0 :(得分:2)

else语句表示没有输入某些条目。

此外,您可以使用splice方法...这样可以减少代码,但速度也会降低。

var data = ['D-0','D-1','D-2','D-3','D-4','D-5','D-6','D-7','D-8','D-9'];

var cells= data.slice(0);;
cells.splice(1, 0, "TEST");
cells.splice(5, 0, "TEST");
cells.splice(6, 0, "TEST");
console.log(cells);

alert(cells);

如果你想看到速度上的差异:

http://jsfiddle.net/DBhPB/1/

更新

更快的解决方案是预先分配数组大小,而不是使用push方法。

var data = ['D-0', 'D-1', 'D-2', 'D-3', 'D-4', 'D-5', 'D-6', 'D-7', 'D-8', 'D-9'];

var cells = new Array(data.length + 3);

var d = 0,
    insertions = 0,
    lenD = cells.length;


while (d < lenD) {

    if (d === 1 || d === 5 || d === 6) {
        cells[d] = 'test';
        insertions++;
        d++;
    }
    else
     {
     cells[d] = data[d-insertions];
     d++;
     }    
}

alert(cells);