Question

I'm getting mixed results by using the splice method in JS with the following example:

var test = function(x){  
    var f = x.toString().length;
    var bb = [];
    for (i=0;i<f;i++){bb.push('a');}
    console.log(bb);
    for (i=bb.length; i>-1; i=i-3){bb.splice(Number((i-2)),1,'b');}
    console.log(bb);    
};              
test (412289847863);

When the length of the input number is 4, 7, 10, 13 and so on, the last element of 'bb' turn to 'b' and I can't see why. As I see it, it should always be 'a'. Why isn't it?

Was it helpful?

Solution

According to your comments you can try this code. You only need one loop and should avoid splice since it's very costly and not needed if you want to replace just one single element at a time.

function test(a){
    var l = a.toString().length;
    var bb = [];
    for (var i = l;i>0;i-=1){
        bb[i-1] = ((l-i+2)%3!=0)?"a":"b";
    }
    console.log(bb);
}

test(1343332);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top