简体   繁体   English

为什么此函数总是返回“ true1”

[英]Why does this function always return “true1”

This is a bit of a modified version of an example in the book 'Eloquent JavaScript'. 这是“ Eloquent JavaScript”一书中示例的修改版本。 Need to understand why it always returns "true1". 需要了解为什么它总是返回“ true1”。 The idea was to find a certain text in the DOM but somehow even if I give a text that does not exist in the html still get "true1" on console. 这个想法是在DOM中找到一个特定的文本,但是即使我给出了html中不存在的文本,在控制台上仍然会得到“ true1”。

Please Help 请帮忙

My HTML File: 我的HTML文件:

<!DOCTYPE html>

 <html> 
    <head>      
        <meta charset="UTF-8" />        
        <title> My first JS page</title>
        <script src="script1.js"></script>
    </head> 
    <body>      

        <h1>My first page</h1>
        <p> Hello , I am Mehdi and this is my first page</p>
        <p> And this is the second paragraph on this page and</p>
    </body>
 <script>console.log(talksAbout(document.body, "Tester123"));</script>
</html>

My Javascript File 我的Javascript文件

function talksAbout(node, string){

    if(node.nodeType == document.ELEMENT_NODE){

        for(var i=0; i<node.childNodes.length; i++){

            if(talksAbout(node.childNodes[i], string))
                return "true1";
        }
        return "false1";
    }else if(node.nodeType == document.TEXT_NODE){

        return node.nodeValue.indexOf(string) > -1;
    }


}

Your function uses the return value of the talksAbout() function as if it were a boolean value. 您的函数使用talksAbout()函数的返回值,就好像它是一个布尔值一样。 However, the function may return a boolean or it may return one of those two string values, "true1" or "false1" . 但是,该函数可能返回布尔值, 或者可能返回这两个字符串值之一"true1""false1" "true1" "false1" Both of those will appear to be true when used in a boolean context like that if statement around the recursive call. 当在布尔上下文(例如,围绕递归调用的if语句)中使用时,这两种方法都将显示为true

Pointy's answer describes one of the two key problems. Pointy的答案描述了两个关键问题之一。 The other is that your search string actually is in the document! 另一个是您的搜索字符串实际上在文档中!

You include the script tag with the search string as part of the document. 您将带有搜索字符串的脚本标签作为文档的一部分。 It will get checked as well as you walk the DOM, and so even after you fix the boolean values, you will still return true as long as you have lines like this in the document: 在遍历DOM的同时也会对其进行检查,因此,即使您修复了布尔值,只要在文档中包含以下行,您仍将返回true

<script>console.log(talksAbout(document.body, "Tester123"));</script>
                                               ^^^^^^^^^  

You could simply run a test from a web developers' console to see this running without such an issue. 您可以简单地从Web开发人员控制台运行测试以查看运行情况,而不会出现此类问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM