简体   繁体   中英

My js array wont display with console.log in chrome browser

console.log doesn't display what I want it to show in my chrome browser dev console.

I have this code:

<!DOCTYPE html>

<html>

 <head>

  <meta charset="utf-8">

  <title></title>

 </head>

 <body>
  <script src="script.js">
       console.log(amazingCars);
       var amazingCars =["BMW","Lexus","Ford","Mercedes"]; 
       amazingCars.pop();
       console.log(amazingCars);
       amazingCars.sort();
       console.log(amazingCars);
       amazingCars.length;
       console.log(amazingCars.length);
   </script> 
 </body>

</html>

The directions for the assignment are the following:

Link the JavaScript page to the HTML page.
Create an array named amazingCars that contains four values:
    BMW
    Lexus
    Ford
    Mercedes
Remove the last value from the array
Next, sort the array in alphabetical order
Lastly, find the length of the array

I dont understand why it isn't displaying or the reason of this issue

You have to change <script src="script.js"> to <script> .

Alternatively you can keep it this way and create a script.js file and copy paste all the code you have inside the <script> tag to the file. This file need to be in the same folder as your index.html file.

Firstly, make the <script src="index.js"></script> seperate from the code in the head, also unless if you have a seperate javascript file you dont need the src part at all, and secondly the first console.log outputs it before definition, creating an error. I hope this helped

If you are putting your JS code in html just add them between <script></script> tag.

You do not need to add src for script unless your JavaScript code is coming from a separate script file.

The src attribute specifies the URL of an external script file .

If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again. Save the script file with a .js extension, and then refer to it using the src attribute in the <script> tag

.

As per the instructions that you are following : "Link the JavaScript page to the HTML page."

  1. Create another file "index.js" in your project directory.
  2. Move your js code into the index.js file in your project directory and then use :

    <script src="index.js"></script> in your HTML.

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