简体   繁体   中英

Looping through array using splice method infinite loop javascript

When i loop through the array using the splice method, the page just freezes. It looks like i caused an infinite loop. lib.randomInt() works, so that is not the problem.

function() {
return function(string) {
    var arr = string.split("")
    arr.sort();
    for(var i = 0; arr.length;i++){
        arr.splice((i+1),0,lib.randomInt(9));
    }
    var pseudocryptarr = arr.join("");
}
})()("example");

This is from a different file that is placed above the main file in html

var lib = {
factorial: function(num){
  function _factorial(num){
    if(num === 1){
        return 1;
        } else {
            return num*_factorial(num-1);
        }
    }
    console.log(num+"! = " + _factorial(num));
    },
    randomInt: function(int,offset){
        if(offset == undefined || null || NaN){
            offset = 0;
        }
        return Math.floor(Math.random()*int)+offset;
    },
    display: function(m, fn){
        fn(m);
    }
};

修改数组本身时,您必须反向循环,以免破坏像这样的循环...

for (var i=arr.length-1; i>=0; i--){}

I fixed it. I wanted after each character for there to be a number. Using the pre-looped array length and doubling it while iterating twice, means that the splice adds the number after the new number element and then the character.

Edit: My typo was the problem. I didnt even have to use len, just iterate by 2.

for(var i = 0;i < arr.length;i+=2){
  arr.splice((i+1),0,lib.randomInt(9));
}

(function() {
    return function(string) {
        var arr = string.split("")
        arr.sort();
        var len = arr.length
        for(var i = 0;i < len*2;i+=2){
            arr.splice((i+1),0,lib.randomInt(9));
        }
        var pseudocryptarr = arr.join("");
        console.log(pseudocryptarr);
    }
})()("example");

Edit: user4723924 method is better:

(function() {
    return function(string) {
        var arr = string.split("")
        arr.sort();
        for(var i = arr.length;i >= 0;i--){
            arr.splice((i+1),0,lib.randomInt(9));
        }
        var pseudocryptarr = arr.join("");
        console.log(pseudocryptarr);
    }
})()("example");

I guess that you wanted to insert a random value after every array element, so that the string "example" would become something like "e5x9a2m4p7l1e3"

There are two issues:

  • Your for loop has no end condition that will become false. You need to state i < arr.length instead of just arr.length which is always truthy for non-empty arrays.

  • You add array elements in every iteration, but then also visit them in the next iteration, and from there on you will only be visiting the new inserted values and never get to the next original element that keeps being 1 index away from i . You need to increment i once more. For that you can use ++i instead if i+1 as the splice argument.

So your loop should be:

    for(var i = 0; i < arr.length; i++) {
        arr.splice(++i,0,lib.randomInt(9));
    }

 const lib = { randomInt: n => Math.floor(Math.random()*n) }; (function() { return function(string) { var arr = string.split("") arr.sort(); for(var i = 0; i < arr.length; i++) { arr.splice(++i,0,lib.randomInt(9)); } var pseudocryptarr = arr.join(""); console.log(pseudocryptarr); } })()("example"); 

Or to save an addition:

    for(var i = 1; i <= arr.length; i+=2) {
        arr.splice(i,0,lib.randomInt(9));
    }

 const lib = { randomInt: n => Math.floor(Math.random()*n) }; (function() { return function(string) { var arr = string.split("") arr.sort(); for(var i = 1; i <= arr.length; i+=2) { arr.splice(i,0,lib.randomInt(9)); } var pseudocryptarr = arr.join(""); console.log(pseudocryptarr); } })()("example"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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