JSON数组索引顺序

时间:2014-10-15 23:52:34

标签: javascript arrays json indexing

有一个系统可以输入文本行作为数组,例如,数组[123,556," test",0,0]。当使用val()。split(' \ n')时,我可以将每个新行添加到新数组中,以便每个行索引增加1,例如,

array[123,556,"test",0,1] = "line 1"
array[123,556,"test",0,2] = "line 2"
array[123,556,"test",0,3] = "line 3"
array[123,556,"test",0,4] = "line 4"

但我需要反向显示最后两个索引。数组需要如下所示:

array[123,556,"test",1,0] = "line 1"
array[123,556,"test",2,0] = "line 2"
array[123,556,"test",3,0] = "line 3"
array[123,556,"test",4,0] = "line 4"

不知何故,他们能够让数组索引在第4个索引中递增。我只能让它在第5个索引中增加..我试过.push(0)在结尾添加0但是得到错误。

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

一种可能性是将索引拼接(移除)到数组之外,然后将其推回到数组的末尾。

var arr = [123,556,"test",0,1];
console.log(arr);  // [123, 556, "test", 0, 1] 

arr.push( arr.splice(3,1)[0] );
console.log(arr); // [123, 556, "test", 1, 0]

http://jsfiddle.net/5wxcd3ux/