HTML, JavaScript and ERR_FILE_NOT_FOUND error

I have a simple html page with javascript code.

HTML

<!doctype html>
<html>
   <head>
      <meta charset="utf-8" />
      <title>Sink The Battle Ship</title>
   </head>
   <body>
      <h1>Battleship</h1>
      <script src="battleship.js"></script>
   </body>
</html>

Javascript

var location = Math.floor(Math.random() * 5);
var numberOfGuesses = 0;
var isSunk = false;
var guess;
var guess = prompt("Ready, aim, fire! (enter a number from 0-6):");
var guessedLocation = parseInt(guess);
console.log(guess);
console.log(guessedLocation);

Each time I run html in a browser, a prompt appears, and when I enter a value, it gives me the error "ERR_FILE_NOT_FOUND". It looks like the browser is trying to redirect to the page with the value I entered. Any idea what is going wrong here? I tried to open html in different browsers and still no luck.

+4
source share
1 answer

The problem is that you are overriding a global variable called location.

When you declare such a variable

var location = 1;

- this is the same as when performing

window.location = 1;

- , , () .

:

1 - : $location, location_2, my_location

var myLocation = Math.floor(Math.random() * 5);

2 -

(function(){
    var location = Math.floor(Math.random() * 5);
    var numberOfGuesses = 0;
    var isSunk = false;
    var guess = prompt("Ready, aim, fire! (enter a number from 0-6):");
    var guessedLocation = parseInt(guess);
    console.log(guess);
    console.log(guessedLocation);
})()

, , ONE 'var'

(function(){
  var location = Math.floor(Math.random() * 5);
  var numberOfGuesses = 0;
  var isSunk = false;
  var guess;
  var guess = prompt("Ready, aim, fire! (enter a number from 0-6):");
  var guessedLocation = parseInt(guess);
  console.log(location);
  console.log(guessedLocation);
  guessedLocation == location ? console.log('you sank me!') : console.log('ha! missed...')
})();
<!doctype html>
<html>
   <head>
      <meta charset="utf-8" />
      <title>Sink The Battle Ship</title>
   </head>
   <body>
      <h1>Battleship</h1>
      <script src="battleship.js"></script>
   </body>
</html>
+3

Source: https://habr.com/ru/post/1670202/


All Articles