将python代码移植到javascript

时间:2009-05-16 12:45:33

标签: javascript python porting

indices[i:] = indices[i+1:] + indices[i:i+1]

希望有人帮忙。

2 个答案:

答案 0 :(得分:6)

我对Python很新,但如果我正确理解代码,它会将给定偏移的列表重建为偏移+ 1后的每个项目和偏移处的项目。

运行它似乎证实了这一点:

>>> indices = ['one','two','three','four','five','six']
>>> i = 2
>>> indices[i:] = indices[i+1:] + indices[i:i+1]
>>> indices
['one', 'two', 'four', 'five', 'six', 'three']

在Javascript中可写:

indices = indices.concat( indices.splice( i, 1 ) );

相同的整个序列将会出现:

>>> var indices = ['one','two','three','four','five','six'];
>>> var i = 2;
>>> indices = indices.concat( indices.splice( i, 1 ) );
>>> indices
["one", "two", "four", "five", "six", "three"]

这是有效的,因为splice对数组具有破坏性,但会返回已删除的元素,然后可以将其传递给concat

答案 1 :(得分:1)

您需要查看Array.slice()

var temp=indices.slice(i+1).concat(indices.slice(i, i+1));
var arr=[];
for (var j=0; j<temp.length; j++){
   arr[j+i]=temp[i];
}