JavaScript 如何创建一个if语句,检查变量是否等于特定的单词
在本文中,我们将讨论如何在JavaScript中创建一个if语句,以检查变量是否等于特定的单词。在JavaScript中,if语句是一种基本的控制结构,允许根据指定的条件有条件地执行代码。一个常见的用例是检查变量的值是否等于特定的单词或字符串。
下面列出了几种可以用来检查变量是否等于特定的单词的方法:
- 使用等号运算符(
===
) - 使用includes()方法
我们将使用示例来探讨上述所有方法及其基本实现。
方法1:使用等号运算符(===
)
使用严格相等运算符(=),它检查变量是否与指定的单词完全相等,包括类型。
语法:
if(variable === 'word') {
// Code to be executed
//if the variable is equal to 'word'.
}
示例: 在这个示例中,我们使用严格相等运算符(=)来检查我们的变量是否等于指定的单词。
JavaScript
let data = 'GeeksforGeeks';
if (data === 'GeeksforGeeks') {
console.log('The variable is equal to "GeeksforGeeks"');
} else {
console.log('The variable is Not equal to "GeeksforGeeks"');
};
输出
The variable is equal to "GeeksforGeeks"
方法2:使用 includes() 方法
在这个方法中,includes() 方法检查字符串 word 是否包含子字符串“gfg”。
语法:
word.includes(targetWord)
示例: 在这个示例中,我们使用上述解决方案。
JavaScript
const word = "GeeksforGeeks";
const targetWord = "gfg";
if (word.includes(targetWord)) {
console.log("The variable contains the word 'gfg'.");
} else {
console.log("The variable does not contain the word 'gfg'.");
};
输出
The variable does not contain the word 'gfg'.