我的 js 数组不会在 chrome 浏览器中显示为 console.log

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

console.log 没有显示我希望它在我的 chrome 浏览器开发控制台中显示的内容。

我有这个代码:

<!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>

作业说明如下:

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

我不明白为什么它没有显示或这个问题的原因

您必须将 <script src="script.js"> 更改为 <script>

或者,您可以保持这种方式并创建一个 script.js 文件,然后将 <script> 标签内的所有代码复制并粘贴到该文件中。此文件需要与您的 index.html 文件位于同一文件夹中。

首先,将 <script src="index.js"></script> 与头部代码分开,除非您有一个单独的 javascript 文件,否则您根本不需要 src 部分,其次是第一个 console.log 在定义之前输出它,造成错误。希望对您有所帮助

如果您将 JS 代码放在 html 中,只需将它们添加到 <script></script> 标记之间即可。

您不需要为脚本添加 src,除非您的 JavaScript 代码来自单独的脚本文件。

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

.

根据您遵循的说明:"Link the JavaScript page to the HTML page."

  1. 在您的项目目录中创建另一个文件 "index.js"。
  2. 将你的js代码移动到项目目录下的index.js文件中,然后使用:

    <script src="index.js"></script> 在你的 HTML.