Javascript拼接方法混乱

时间:2015-09-11 22:32:26

标签: javascript splice

嘿伙计们正在研究一个搜索字符串的问题,并在我的案例中替换x和y之前&后。但由于某种原因,我的splice()方法只是返回已删除的元素。那就是我真正坚持的地方.....看看我的代码,谢谢

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

1 个答案:

答案 0 :(得分:2)

这就是splice()的工作方式。它返回已删除的元素,但更改原始数组。如果输出strIntoArray,则应进行更改。