gpt4 book ai didi

Javascript 方法和变量(初学者)

转载 作者:行者123 更新时间:2023-11-30 12:19:16 25 4
gpt4 key购买 nike

我在理解代码时遇到了严重的问题。

function replace(str, before, after) {

var rtt = before;
var rt;

if(before[0] === before[0].toUpperCase()) {
var aa = after.split("");
var u = after[0].toUpperCase();
aa.splice(0,1,u);
rt = aa.join("");
}
else {
rt = after;
}

var r = str.split(" ");
var i = r.indexOf(rtt);
r.splice(i,1, rt);
var join = r.join(" ");
return join;
}

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

我不明白为什么我不能在 r.splice(i,1,rt) 之后执行 r.join("") 然后返回r为什么我必须声明新的变量 join?否则 return 将不会返回正确的语句。不过代码是正确的。

最佳答案

根据 MDN ,

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

这个方法返回什么?

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

就这个问题而言

Why I must declare new variable join ?

实际上,您不必声明新变量。你可以只返回这个值

return r.join(" ");

function replace(str, before, after) {

var rtt = before;
var rt;

if(before[0] === before[0].toUpperCase()) {
var aa = after.split("");
var u = after[0].toUpperCase();
aa.splice(0,1,u);
rt = aa.join("");
}
else {
rt = after;
}

var r = str.split(" ");
var i = r.indexOf(rtt);
r.splice(i,1, rt);
return r.join(" ");
}

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

document.write(replaced);

关于Javascript 方法和变量(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31554357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com