What does text != "" mean?

What does text != "" mean?

本文关键字:quot mean does text What      更新时间:2023-09-26

摘自雄辩Javascript第6章:

代码:

 function splitParagraph(text) {
     var fragments = []; 
     while( text != "" )                         // ?
         if (text.charAt(0) == "*") {
               fragments.push({type: "emphasized"});
 etc...

我很难掌握while循环在做什么。Text是一个字符串。while循环是否读取"while text没有任何剩余字符…"while循环是否一个接一个地查看字符串中的每个字符,以确保还有一个字符剩余?

当内部条件为真时,while循环继续运行。在本例中,如果所讨论的字符串不是空字符串,则text != ""为true。

在这个特殊的情况下,我猜text必须在循环中的某个地方改变,否则在这里使用while结构是没有意义的。

:实际上,在JavaScript中,!===运算符将以一种非常奇怪的方式计算:例如,0,[]""将被认为是相等的:

  • "" != [] -> false
  • 0 != [] -> false
  • 0 != "" -> false

===!==可以用来强制严格相等

检查文本是否为空字符串(长度为0且不包含字符)。

"Is the while loop looking at every character in the string 
one by one making sure there is another character left?"

是的,虽然没有显示整个循环,但几乎可以肯定正在做的是

while条件检查text字符串是否为空。如果不为空,则循环遍历循环体。text.charAt(0)检查字符串的第一个字符。如果找到'*'字符,一个元素被添加到fragments数组。

在正文中,将有代码删除text字符串的第一个字符然后循环处理字符串的下一个字符。

while( text != "" )                        
         if (text.charAt(0) == "*") {
               fragments.push({type: "emphasized"});

text != " "是什么意思?

表示如果text的值不能强制匹配""

考虑以下代码

if ("abc" != "") {
    console.log("1 ok");
}
if ([] != "") {
    console.log("2 ok");
}
if (0 != "") {
    console.log("3 ok");
}
if (false != "") {
    console.log("4 ok");
}
在jsfiddle

哦,天哪,情况2、3和4发生了什么?