If条件在javascript中比较时不起作用
if condition not working in javascript when comparing
我试图通过一个单词循环并检查是否存在一个特定的字母,但由于某种原因,if语句中的条件不工作。
Main.UpdateLetter = function(letter) {
Main.Changes = 0;
for(i = 0 ; i < Main.word.length ; i++){
Main.wordArray[i] = Main.word.charAt(i);
console.log(Main.wordArray[i]);
if ( Main.wordArray[i] == d ) {
alert("found letter");
} else {
console.log("not found");
}
}
}
为什么要这样做JavaScript为您提供了许多选项,您可以使用JavaScript字符串包括()或indexOf()方法
包括()方法
var str = "Hello world, welcome to the universe.";
var n = str.includes("world");
n的结果将是:trueincludes()方法确定字符串是否包含指定字符串的字符。
如果字符串包含该字符,则返回true,否则返回false。
indexOf()方法
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
n的结果将是:13方法的作用是:返回指定值在字符串中第一次出现的位置。
如果要搜索的值从未出现,该方法返回-1。
也许你想用一种复杂的方式来做。尝试IndexOf函数。此方法返回字符串中指定值第一次出现的位置。如果要搜索的值从未出现,则此方法返回-1例如:
var x = Main.word.indexOf("d");
if( x > -1 ){
alert("found letter at position "+x);
}
else{
alert("Letter not found");
}
我觉得这就是你想要的!
for (var i = 0, len = Main.word.length; i < len; i++) {
if(Main.word.charAt(i) == "A"){
alert("found letter");
}else{
console.log("not found");
}
}
很难弄清楚你想做什么,我怀疑你正试图使用OOP方法来查找某个字符串中是否存在字母,或者可能方法名称UpdateLetter
意味着你想用其他字符串替换字母…
下面是一个示例实现,如何使用原型继承构造函数和replace方法来实现:
// object type definition (sometimes called "class")
function Main (word) {
this.word = word;
};
Main.prototype.wordHasLetter = function(letter) {
return this.word.indexOf(letter) !== -1;
};
Main.prototype.replaceLetterInWord = function(letter, replacement) {
var regex = new RegExp(letter, "g");
this.word = this.word.replace(regex, replacement);
};
// create instance of the type Main
var main = new Main("abcabc");
// sample usage of the methods
console.log("main.word is:", main.word)
if (main.wordHasLetter("a")) {
console.log("found letter")
} else {
console.log("not found")
}
main.replaceLetterInWord("a", "x");
console.log(main.word);
相关文章:
- 替换函数后的Javascript比较字符串不起作用
- 字符串比较在d3.rgb中不起作用
- 比较应用程序脚本中的两个数组不起作用
- Javascript 比较时间不起作用
- jQuery this.href 字符串比较不起作用
- 字符串比较不起作用
- Javascript数字变量比较不起作用
- Javascript中的字符串比较不起作用
- d3 本地存储比较数组 .filter 咖啡脚本;数组变量不起作用
- j查询帖子数据返回比较不起作用
- 将数组从文档属性与数据范围进行比较不起作用
- JavaScript 比较运算符不起作用
- 为什么我的比较不起作用
- Angular JS===比较不起作用
- 与-1或未定义进行比较不起作用,无论是使用==还是===
- Javascript字符串比较不起作用
- 在$filter应用于3位数的负数之后,小于比较不起作用
- dhtmlxform.发送的响应在警告提示中正确显示,但字符串比较不起作用
- 或者比较不起作用
- Javascript风格比较不起作用