ken
ken

Reputation: 5086

port python code to javascript

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

Hope someone helps.

Upvotes: 0

Views: 673

Answers (2)

Borgar
Borgar

Reputation: 38644

I'm fairly new to Python but if I understand the code correctly, it reconstructs a list from a given offset into every item following offset+1 and the item at the offset.

Running it seems to confirm this:

>>> 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']

In Javascript can be written:

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

Same entire sequence would go:

>>> 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"]

This works because splice is destructive to the array but returns removed elements, which may then be handed to concat.

Upvotes: 6

Leonard Ehrenfried
Leonard Ehrenfried

Reputation: 1613

You will want to look at 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];
}

Upvotes: 1

Related Questions