Javascript拼接方法混乱
Javascript splice method confusion
大家好,我正在解决一个问题,即搜索字符串并将 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");
这就是 splice() 的工作原理。它 returns 删除了元素,但更改了原始数组。如果输出 strIntoArray,则应进行更改。
大家好,我正在解决一个问题,即搜索字符串并将 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");
这就是 splice() 的工作原理。它 returns 删除了元素,但更改了原始数组。如果输出 strIntoArray,则应进行更改。