简体   繁体   English

Javascript拼接方法问题

[英]Javascript splice method issue

I have a problem with the splice method. 我的拼接方法有问题。 In the script below, if I set the second argument of splice to '0' it crashes my browser. 在下面的脚本中,如果我将splice的第二个参数设置为“ 0”,它将使我的浏览器崩溃。 If I set to any other value that is greater than '0' it works just fine. 如果我将任何其他值设置为大于“ 0”,则可以正常工作。

Why is this happening? 为什么会这样呢?

Thanks, 谢谢,

And the code: 和代码:

function f (x) {

    var d = x.toString().split("");

    for (i=0; i<d.length; i++){
        if (Number(d[i])%2===0){
            d.splice(i, 0, "drum");
        }
    } 

    return d;
};

Its an infinite loop and each time drum is getting inserted to array increasing its length. 它是一个无限循环,每次插入drum到阵列中都会增加其长度。

Splice() insert the item to array so you are inserting new item. Splice()将项目插入数组,因此您要插入新项目。

first loop: 第一循环:

  • Array is 8,8,8 数组为8,8,8
  • i is 0 //d[0] is 8 i是0 // d [0]是8
  • Condition if (Number(d[i])%2===0) is true if (Number(d[i])%2===0)true
  • drum inserted Now Array is drum,8,8,8 drum插入现在阵列是drum,8,8,8

second loop: 第二个循环:

  • Array is drum,8,8,8 数组是drum,8,8,8
  • i is 1 //d[i] is 8 i是1 // d [i]是8
  • Condition if (Number(d[i])%2===0) is true if (Number(d[i])%2===0)true
  • drum inserted Now Array is drum,drum,8,8,8 插入了drum现在阵列是drum,drum,8,8,8

and it goes on.... 然后继续...

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

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