简体   繁体   English

Javascript拼接方法混乱

[英]Javascript splice method confusion

Hey guys im working on a problem that searches the string and replaces x with y in my case before & after. 大家好,我正在研究一个字符串,在我之前和之后,用y替换x的问题。 But for some reason my splice() method is just returning the deleted element. 但是由于某种原因,我的splice()方法只是返回已删除的元素。 and thats where im actually stuck at..... Take a look at my code below, thanks 多数民众赞成在我实际上停留在.....看看下面我的代码,谢谢

    function replace(str, before, after) {
        /* logic 
      1. put the string into an array with split() 
      2. search array index and replace 2nd argument with 3rd argument 
      3. turn array back into string wtih join() method
      */
        // turn string into an array
        var strIntoArray = str.split(' ');

        // looping thru array
        for( i = 0; i < strIntoArray.length; i++){

            //compare index to arguments
            if (strIntoArray[i] === before) {
                // replace index with arguments with splice() method
                // this part is a lot more complex
                console.log(strIntoArray.splice(strIntoArray.indexOf(before), 1, after));

            }
        }

        //console.log(strIntoArray);
    }

replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

That's how splice() works. 这就是splice()的工作方式。 It returns the removed element, but changes the original array. 它返回删除的元素,但更改原始数组。 If you output strIntoArray, the change should be made. 如果输出strIntoArray,则应进行更改。

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

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