Javascript 第三个参数I是否接受任何值?
我不明白为什么纽瓦尔没有改变。似乎我的拼接函数不接受“first13[index]”作为参数。不过,当我将“索引”更改为固定值时,一切都会发生变化。我确实对索引进行了合并,它将正确的值显示为整数。我真的很困惑。有什么建议吗Javascript 第三个参数I是否接受任何值?,javascript,Javascript,我不明白为什么纽瓦尔没有改变。似乎我的拼接函数不接受“first13[index]”作为参数。不过,当我将“索引”更改为固定值时,一切都会发生变化。我确实对索引进行了合并,它将正确的值显示为整数。我真的很困惑。有什么建议吗 function rot13(str) { let first13 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']; let second13 = ['n', 'o', 'p',
function rot13(str) {
let first13 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'];
let second13 = ['n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
let newArr = str.toLowerCase().split('');
let index = 0;
for (let i=0; i<newArr.length; i++) {
if(first13.indexOf(newArr[i]) != -1) {
index = first13.indexOf(newArr[i]);
newArr.splice(i, 1, first13[index]);
console.log(newArr);
}
}
}
rot13("EBG13 rknzcyr.") // "ROT13 example.";
函数rot13(str){
让first13=['a','b','c','d','e','f','g','h','i','j','k','l','m'];
设second13=['n','o','p','q','r','s','t','u','v','w','x','y','z'];
设newArr=str.toLowerCase().split(“”);
设指数=0;
对于(设i=0;i代码运行良好。
你的逻辑有错误。
您只是在用相同的元素替换该元素。
例如,您将用first13(索引)替换E。first13(索引)是E。
如果要将其替换为+13个字符,可以将first13[index]
更改为second13[index]
。
编辑:必须对splice()方法的参数进行上述更改。所有操作都完全按照其编码进行
干运行您的代码:
迭代1:
index=0
i=0
if( first13.indexOf("e") != -1 ) //true
{
index = first13.indexOf("e") //index = 4
newArr.splice(0,1,first13[4]) //at 0th index remove one element and add first13[4] therefore newArr[0] becomes "e" from "e" (basically remains same)
console.log(newArray) . //printing the array which is same as before.
}
迭代2:
index=4 //from last iteration
i=1
if( first13.indexOf("b") != -1 ) //true
{
index = first13.indexOf("e") //index = 1
newArr.splice(1,1,first13[1]) //at 1st index remove one element and add first13[1] therefore newArr[1] becomes "b" from "b" (basically remains same)
console.log(newArray) //printing the array which is same as before.
}
每次迭代后,数组都是相同的,因为您要用相同的元素替换元素,如上所示。重新编写逻辑。您还没有编码您想要做的事情…在当前设置中,代码只是将newArr
中的字母替换为first13
中的相同字母
当代码第一次运行时
index=first13.indexOf(newArr[i]);
正在设置索引=4,然后
newArr.splice(i,1,first13[index]);
是在first13[4]
处取字母,在本例中为“e”,并替换newArr[0]
,该字母也恰好是“e”
正如上面Raj Datta Manohar所建议的,将拼接方法中的最后一个属性更改为second13[index]
你应该更接近你所要寻找的东西。这里的每个人都已经回答了如何更正代码中的逻辑。下面是解决这个问题的另一种方法,可能有助于阅读逻辑,因为这样做会少一些
function rot13(str) {
let input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let output = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';
let index = (x) => input.indexOf(x);
let translate = (x) => index(x) > -1 ? output[index(x)] : x;
console.log(str.split('').map(translate).join(''));
}
rot13("EBG13 rknzcyr."); // ROT13 example.
你想达到什么目的?你想要的结果是什么?我想用数组中的字母替换作为参数传递的字母。例如,“a”变成“n”,因为它是字母表中的+13。好吧,这是有道理的。正如下面提到的,你目前正在用字符本身替换字符。还有一个较短的方法。我将在下面包含我的代码,但请随意使用或不使用。我太专注于编码规则部分,以至于忘记了逻辑部分。非常感谢