[英]Any alternative way of using this .charAt()?
I have a problem, when I used input[index]
in the statement the reverse word didn't match the value of inputString. 我有一个问题,当我在语句中使用input[index]
,反向词与inputString的值不匹配。 But this works in C#. 但这在C#中有效。 When I try it in JavaScript is not working. 当我尝试在JavaScript中无法正常工作时。 I want to learn what are the other alternative way of .char()
method. 我想学习.char()
方法的另一种替代方法。 Can anybody solve my problem? 谁能解决我的问题?
strReverse = "";
input = document.getElementById("inputValue").value;
i = input.length;
for(var j = i; j >= 0; j--) {
strReverse = strReverse + input.charAt(j); // i used input[index]
}
If you wish to use input[index]
instead of input.charAt()
then you need to address the issue that you are setting i = input.length;
如果希望使用input[index]
而不是input.charAt()
则需要解决设置i = input.length;
的问题i = input.length;
So when you enter your loop for the first iteration, j
will be equal to i
. 因此,当您进入第一次迭代的循环时, j
将等于i
。 Meaning that you are trying to access the character at the index equal to the length of the string (when you do input[j]
). 这意味着您正在尝试访问等于字符串长度的索引处的字符(当您input[j]
)。 However, as arrays and string indexing starts at zero in javascript (and in most languages), there is no index at i
(the length of the string), but, there is an index at i-1
, which will give the last character in the string. 但是,由于数组和字符串索引在javascript(和大多数语言)中从零开始,所以在i
(字符串的长度)处没有索引,但是在i-1
处有索引,它将给出最后一个字符在字符串中。 Thus, if you want to reverse your array using input[j]
you need to start j
in your for loop as j = i - 1
. 因此,如果要使用input[j]
反转数组,则需要在for循环中以j = i - 1
开头j
。
Take a look at the snippet for a working example: 看一下示例代码:
strReverse = ""; input = "level"; i = input.length; for(var j = i-1; j >= 0; j--) { strReverse = strReverse + input[j]; // i used input[index] } if(strReverse === input) { alert(input +" is a palindrome!") } else { alert(input +" is not a palindrome!"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.