Console error meaning? - javascript

I'm new to programming and can't figure out what is wrong with this code I'm working on. In the developer console I keep getting these error codes.
Hw%20multifuncion.html:24 Uncaught SyntaxError: Unexpected token ILLEGAL
Hw multifuncion.html:34 Uncaught ReferenceError: compute is not defined
What do these mean? I'm not familiar with the debugger yet so any help would be much appreciated.
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>WindChill</title>
<script type="text/javascript">
/* Input: Temperature in fahrenheit and windspeed in mph
* Processing: Calculate windchill and output to user. While useing two funcions, and assign a call and return.
* Output: The windchill
*/
function compute() {
var temperature = document.getElementById("temperature").value;
var windspeed = document.getElementById("windspeed").value;
var temp = parseInt(temperature);
var wind = parseInt(windspeed);
var result = windChill(temp, wind);
document.getElementById("output").innerHTML = result;
}
function windChill(tempF, speed) {
var f = 35.74 + 0.6215 * tempF− 35.75 * Math.pow(speed, 0.16) + 0.4275 * Math.pow(tempF, 0.16);
}
</script>
</head>
<body>
Temperature (Fahrenheit)
<input type="text" id="temperature" size="5">
<br>Wind speed (MPH)
<input type="text" id="windspeed" size="5">
<button type="button" onclick="compute()">WindChill</button>
<div id="output"></div>
</body>
</html>

The issue is in your windChill function: you are using − instead of a - symbol.
function windChill(tempF,speed) {
var f = 35.74 + 0.6215*tempF - 35.75*Math.pow(speed,0.16) + 0.4275*Math.pow (tempF,0.16);
}

Your windChill function has two issues :
It needs to return a result. As it is now, you assign your computation to f, but you don't do anything with it.
As Darshan points out, it seems your minus - symbol is not the right one.
Simply add return f; after your variable assignment and correct your minus symbol.

Related

How can I add a thousands separator in those lines of code?

I have been googling for this, but I found the solutions difficult, so I came here to ask how can I do it.
I'm doing an incremental game and I want to start with the basics: mining gold and buying. Now I'm moving to my next step at developing this game and I really need help
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Gold Miner</title>
</head>
<body>
<h2 id="goldMined">0 Gold Mined</h2>
<br />
<br />
<button onclick="buyGoldPerClick()" id="perClickUpgrade">Get More Money. Cost: 10 Gold</button>
<br />
<br />
<button onclick="Reset()">Reset Game</button>
<script src="main.js" charset="utf-8" type="text/javascript"></script>
</body>
</html>
JavaScript
var gameData = {
gold: 0,
goldPerClick: 0.01,
goldPerClickCost: 10,
tickReduction: 1000,
tickReductionCost: 100
}
function mineGold() {
gameData.gold += gameData.goldPerClick
document.getElementById("goldMined").innerHTML = gameData.gold.toFixed(0).toLocaleString('en') + " Gold Mined"
document.getElementById("perClickUpgrade").innerHTML = "Buy Pickaxe. Cost: " + gameData.goldPerClickCost.toFixed(0).toLocaleString('en') + " Gold"
}
function buyGoldPerClick() {
if (gameData.gold >= gameData.goldPerClickCost) {
gameData.gold -= gameData.goldPerClickCost
gameData.goldPerClick *= 2
gameData.goldPerClickCost *= 3
document.getElementById("goldMined").innerHTML = gameData.gold.toLocaleString('en') + " Gold Mined"
document.getElementById("perClickUpgrade").innerHTML = "Buy Pickaxe. Cost: " + gameData.goldPerClickCost.toLocaleString('en') + " Gold"
}
}
function Reset() {
gameData.gold = 0
gameData.goldPerClick = 0.01
gameData.goldPerClickCost = 10
}
var mainGameLoop = window.setInterval(function () {
mineGold()
}, 10)
var saveGameLoop = window.setInterval(function () {
localStorage.setItem("goldMinerSave", JSON.stringify(gameData))
}, 1)
var savegame = JSON.parse(localStorage.getItem("goldMinerSave"))
if (savegame !== null) {
gameData = savegame
}
Any help supports a lot for me, as I am a JavaScript and HTML programming beginner! Thanks for reading my post!
You can use the NumberFormat() function from the Intl API available in Javascript. (click on the link for documentation).
The first parameter to the Intl.NumberFormat() function is the locale, if you want it to be generic, just pass in 'en-US'. But if you can also pass in navigator.language if you want to just take the language from the browser.
The second parameter to this function is an options object. Now, within this options object, I have passed in the maximumSignificantDigits and set it to 3. You can change that as per your requirements. You also have other options you can pass in, just check out the link I provided above.
Finally, you will be calling the format() function and passing in your gold as the parameter, and this will overall return you the formatted value with 3 maximum significant digits.
const gold = 1000000;
const formattedGold = Intl.NumberFormat('en-US', { maximumSignificantDigits: 3 }).format(gold);
//Printing output to console
console.log(formattedGold);

pickRandom is not defined (JavaScript)

{
var word = pickRandom([
'Quacks' ,
'eats',
'Hoots',
]);
print('the owl' + word + 'at midnight');
}
I've seen examples use arrays this way, but when I plug it in into my coding software , either nothing appears or it claims that pickRandom is undefined
What am I doing wrong?
pickRandom isn't a real function! Print doesn't exist in Javascript! Here is how to do it :
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
function pickRandom() {
var wordsarray= ['Quacks', 'eats', 'Hoats'];
var randomnumber = Math.floor(Math.random() * wordsarray.length);
document.write(wordsarray[randomnumber]);
}
</script>
<button value="clickme" onclick="pickRandom()">Click Me To Pick A Random Word!</button>
</body>
</html>
create a pickRandom function:
function pickRandom(warray){
var randomNumber = Math.floor(Math.random() * warray.length);
return warray[randomNumber];
}
var words=['Quacks',
'eats',
'Hoots'];
var random=pickRandom(words);
console.log(random);

javascript read number of hours worked

Write the JavaScript to read the number of hours worked from the user. Then write the JavaScript to calculate how much money the user made if they were paid $12/hour for the first 40 hours worked, and $18/hr for all hours worked over 40. Then use the alert() function to print the total amount to the user.
what code do I have to use
var y = prompt("Enter a Value","");
Lol #OverComplicated. The answer is there just remake a better version and try your homework before being spoonfed.
var BarryScott = {
PricePerHour: 12,
HoursWorkedByBarry: 0,
PrintPayment: function() {
if ( this.HoursWorkedByBarry > 40) {
var RemainHours = this.HoursWorkedByBarry - 40;
alert(this.PricePerHour * 40 + RemainHours * 18);
} else {
alert(this.PricePerHour * this.HoursWorkedByBarry);
}
},
AskHoursFromBarry: function() {
this.HoursWorkedByBarry = prompt("Enter Hours you worked");
this.PrintPayment();
}
}
BarryScott.AskHoursFromBarry();
Create a folder and place your index.html and javascript code inside.
Run index.html .
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Im lazy to do my assignment</title>
<script src = "billhours.js"></script>
</head>
<body>
</body>
</html>
billhours.js
var getInput = prompt("Enter Number of Hours worked");
var first40hrs = billHours(40, 12);
var over40hrs = billHours(getInput - 40, 18);
var totalSalary = first40hrs + over40hrs;
alert("Total Salary is "+totalSalary);
function billHours(hours, rate){
return hours*rate;
}
//This function only works for hours 40 and above.
//It's your job to put conditional statements if hours is below 40. Keep Coding.

Form button keeps showing results in new window

Very new to html and javascript here. I get the following form up and it calculates correctly but the result shows up in a new page. I'd like it to stay in the same page. Not sure what I did wrong here. Also, is there any way to shorten the function? Seems like a lot of work to do a simple calculation. Any help would be great.
<html>
<head>
<title>Help!</help>
<script type="text/javascript">
function add(x,y){
var x = document.add1.add2.value;
var y = document.add1.add3.value;
var x = Number(x);
var y = Number(y);
var z = x+y;
return (z);
}
</script>
</head>
<body>
<h3>Help me stack overflow you're my only hope!</h3>
<form name="add1">
Input first number to add: <input type="number" name="add2">
2nd number: <input type="number" name="add3">
<input type="button" value="Result"
onclick = "document.write('The total is: ' + add() + '.');" />
</body>
</html>
Dont' use document.write to display data, it overwrites entire document. You don't want that. It's better to create new function which would render result into some other element:
<input type="button" value="Result" onclick="showResult('The total is: ' + add() + '.');" />
and the showResult function can be for example:
function showResult(result) {
document.getElementById('result').innerHTML = result;
}
HTML:
<div id="result"></div>
Demo: http://jsfiddle.net/7ujzn35c/
Here are also a couple of general improvements you can make your code:
move string manupulations to showResult completely:
<input type="button" value="Result" onclick="showResult()" />
http://jsfiddle.net/7ujzn35c/1/
call add from inside showResults
onclick="showResult(this.form.add2.value, this.form.add3.value)"
http://jsfiddle.net/7ujzn35c/2/
<title>Help!</help>
First of all, This should be <title> Help! </title>
Secondly, document.write function actually starts writing the entire page anew.
You should either replace onclick = "document.write('The total is: ' + add() + '.');" with
onclick = "alert('The total is: ' + add() + '.');"
Better still, you could create a div element like so
<title> Help! </title>
<script>
.....
</script>
</header>
<body>
<div id = 'output'> </div> ...
then
`onclick = "document.getElementById("output").innerHTML = 'The total is: ' + add() + '.';"
And don't give up. Hope this helps you

Modifying the integer at the end of a string

I am in need of your assistance,
What I need is a javscript function that would accomplish one of two things:
Firstly, if given a string, ie. var x = "filenumber" the function when called, would process the string and add a -2 to the end of it, resulting in var x = "filenumber-2" if the -2 does not exist on the end of the string.
Secondly, if the given value, var x is already = "filenumber-2" then take the number at the end of the string and increment it by 1, resulting in var x = "filenumber-3". and so fourth incrementing the number every single time after that, if the function is called again.
Here is the concept markup:
<DOCYTPE HTML>
<html>
<head>
<script type="text/javascript">
function test(){
var x = document.getElementById('input').value
1.) if x doesnt already have the -2 at the end of the string then add it:
document.getElementById('output').value = x + "-2"
2.) else, the function recognizes that it does and the result of the output is
x-2 + 1
}
</script>
</head>
<body>
<input type="text" id="input"/>
<br>
<input type="text" id="output"/>
<br>
<input type="button" onclick="test()" value="test"/>
</body>
</html>
Short 'n sweet:
x = 'filenumber-4';
x = x.replace(/^(.+?)(-\d+)?$/, function(a,b,c) { return c ? b+(c-1) : a+'-2'; } );

Categories

Resources