简体   繁体   English

JavaScript splice()方法出现问题

[英]Issue with JavaScript splice() method

I'm getting mixed results by using the splice method in JS with the following example: 我通过以下示例在JS中使用splice方法获得混合结果:

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. 当输入数字的长度为4、7、10、13等时,“ bb”的最后一个元素变为“ b”,我不知道为什么。 As I see it, it should always be 'a'. 如我所见,它应该始终为“ a”。 Why isn't it? 为什么不呢

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM