0

我需要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

*/
4

1 回答 1

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);
于 2013-09-19T11:55:23.270 回答