简体   繁体   中英

Include JavaScript file in HTML won't work as <script … />

I have two files in a folder :

  1. main.html
  2. main.js

The main.js as follows:

function revertNum(num){
    var strNum = new String(num);
    var strArr = strNum.split();
    var result = '';
    for(var i = strArr.length - 1; i > 0; i--){
        result += strArr[i];
    }
    return result;
}
var x = revertNum(32132);
console.log(x);

The main.html as follows:

<html>
    <head>
        <meta charset="utf-8" />
        <script src="main.js"></script>
    </head>
    <body>
    </body>
</html>

I expected console of browser will show reverse of 32132 , but it only show SRC of main.js file.

Here is the output 在此处输入图片说明

You are not actually adding anything to your result. You are logging a line, but it is an empty string.

That being said... try this instead for reversing a string inside of main.js. It is so much more simple and relieves the function of all that code.

 function revertNum(num) { return String(num).split('').reverse().join(''); } var x = revertNum(32132); console.log(x); 

There are two errors in your code:

  1. Your split line should give "" as a delimiter: var strArr = str.split("");

  2. Your loop condition should be i >= 0 , not i > 0

You're seeing just a blank in the console output because the first error means that strArr is an array with just one element: "32132" , and the second error means you stop before processing the last (only) element in the array and return "" .

In future, you can find this out for yourself by using the debugger built into your browser:

  1. Add debugger; at the top of main.js -- later, when you're more familiar with the tools, you won't need to do that, but for now it's the easiest way to get you into the debugger

  2. Open a tab

  3. Use the menus to open your "developer tools" (it's F12 or Ctrl+Shift+I or Cmd+Shift+I on most browsers) Now that I see you're using Firefox, from the menus it's Web Developer > Debugger (Ctrl+Shift+S, although Ctrl+Shift+I works to open dev tools, then you just click the Debugger tab).

  4. Open your page. That should switch you to the "Source" or "Sources" or "Debugger" tab in the developer tools with your source code in front of you. (It's "Debugger" in Firefox's built-in tools.)

  5. Use the various tools there to step through the code statement-by-statement, look at the values of variables, etc.

You'll want to find the Developer Tools website for your browser's tools to find out how to use them. This question and its answers have a lot of useful links to those. Firefox's built-in tools are covered here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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