Javascript: gradually adding to string in each iteration?
I have a string like this that is split up:
var tokens = "first>second>third>last".split(">");
What I would like in each iteration is for it to return
Iteration 0: "last"
Iteration 1: "third>last"
Iteration 2: "second>third>last"
Iteration 3: "first>seco开发者_如何学编程nd>third>last"
I am thinking of using decrementing index for loop.... but is there a more efficient approach ?
for (int w = tokens.length-1; w == 0; w--)
{
}
var tokens = "first>second>third>last".split(">");
var out = []
while(tokens.length) {
out.unshift(tokens.pop());
console.log(out.join('>'))
}
OTOH this is the simplest aproach
var tokens = "first>second>third>last".split(">");
text = ''
for (w = tokens.length-1; w >= 0; w--)
{
if(text != ''){
text = tokens[w] + '>'+text;
}else{
text = tokens[w]
}
console.log(text);
}
You could try the following:
var tokens = "first>second>third>last".split(">");
for (var w = 0; w < tokens.length; w++)
{
var substr = tokens.slice(tokens.length - 1 - w, tokens.length).join(">");
console.log("Iteration " + w + ": " + substr)
}
You could also use join to reverse the original split. I'm not sure about efficiency but it's quite legible:
var tokens = 'first>second>third>last'.split('>');
for (var i = tokens.length - 1; i >= 0; --i) {
var subset = tokens.slice(i).join('>');
console.log(subset);
}
var tokens = "first>second>third>last".split(">");
var text = [];
for (var i = tokens.length; --i >= 0;) {
text.unshift(tokens[i]);
var str = text.join(">");
alert(str); // replace this with whatever you want to do with str
}
Should do the trick.
精彩评论