pickRandom is not defined (JavaScript) - 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);

Related

Javascript identical if else statements behaving differently /not outputting HTML

I am new to JS and was trying to practice conditionals when I ran into this really weird problem.
Each conditional is working as intended in the sense that when the desired condition is met, the code is executed, for example, console.log() is outputting exactly what I want it to but trying to output the same to HTML is not working for some reason.
My code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<title>Tester</title>
</head>
<body>
<p id="test"></p>
<script>
const max = 5;
const ranNumber = Math.floor(Math.random() * max) + 1;
console.log(ranNumber);
let correct = false;
while (!correct) {
let guess = prompt("Guess a Number 1 - " + max);
guess = Number(guess);
if (guess === ranNumber) {
correct = true;
$("#test").html("Your guess was correct!");
} else if (guess > ranNumber) {
$("#test").html("Your guess was too high!");
} else {
document.getElementById("test").innerHTML = "Your guess too low!";
}
}
</script>
</body>
</html>
Now, I am using Jquery to write the HTML to the p tag but I also tried it like this:
<!DOCTYPE html>
<html>
<head>
<title>Tester</title>
</head>
<body>
<p id="test"></p>
<script>
const max = 5;
const ranNumber = Math.floor(Math.random() * max) + 1;
console.log(ranNumber);
let correct = false;
while (!correct) {
let guess = prompt("Guess a Number 1 - " + max);
guess = Number(guess);
if (guess === ranNumber) {
correct = true;
document.getElementById("test").innerHTML = "Your guess was correct!";
} else if (guess > ranNumber) {
document.getElementById("test").innerHTML =
"Your guess was too high!";
} else {
document.getElementById("test").innerHTML = "Your guess too low!";
}
}
</script>
</body>
</html>
Your page can't load while you're in the while loop and using prompt halts your javascript until it gets an input. Here's a link to a similar question that was asked:
https://www.reddit.com/r/webdev/comments/p8vod8/very_new_to_js_why_does_the_html_text_not_load/
A much better way which is also pretty easy is using an input field and a button. the onclick option runs your function
<input type="number" id="input">
<button onclick="guess()">Guess</button>
And your javascript can look like this
const max = 5
const ranNumber = Math.floor(Math.random() * max) + 1
console.log(ranNumber)
function guess(){
let input = document.getElementById('input').value
let text = document.getElementById('test')
if(input == ranNumber){
text.innerHTML = "You guessed it!"
}
else{
text.innerHTML = "Wrong!"
}
}
The fact that yr code does work! can be seen in the debugger,
but only that the loop runs to fast that you can't see it,
Congrats, for your use of 'const, Number(),' guess === ranNumber assignment operator given that, you say U are new to JS
So to output it to Html, you would need a little bit of adjustment!

Substring assignment

I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.

Console error meaning?

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.

Difference between passing a string to a function versus calling the function with a default parameter?

I have made a small application that increments a counter when a picture of a cat is clicked. When I set the function with default parameters, it works. However, when I pass it a string to substitute in the function, it does not. What is the difference between these two scripts?
The first script, which does not pass a string to the catClick function:
'use strict';
function CatCount (pic_url, cat_name) {
this.pic_url = pic_url;
this.click_count = 0;
this.cat_name = cat_name;
return false;
}
var cat_name;
var pic_url;
var click_count;
function catClick() {
var cat_click_p = document.getElementById("number_clicked");
var number = cat_click_p.innerHTML;
number = parseInt(number) + 1;
cat_click_p.innerHTML = number;
}
var catGrid = document.getElementById('cat_grid');
catGrid.addEventListener('click', catClick, false);
and the second version of the script, which does pass a string to the catClick function:
'use strict';
function CatCount (pic_url, cat_name) {
this.pic_url = pic_url;
this.click_count = 0;
this.cat_name = cat_name;
return false;
}
var cat_name;
var pic_url;
var click_count;
function catClick(element_id_to_be_replaced) {
var cat_click_p = document.getElementById(element_id_to_be_replaced);
var number = cat_click_p.innerHTML;
number = parseInt(number) + 1;
cat_click_p.innerHTML = number;
}
var catGrid = document.getElementById('cat_grid');
catGrid.addEventListener('click', catClick('number_clicked'), false);
The second version of the script just increments the cat counter once.
Additionally, here is the index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src='js/app.js'></script>
<title>Cat App</title>
</head>
<body>
<div>
This app keeps track of how many times you click on a cat!
<div class='cat' id='cat_grid'>
<img src='http://thepetproductguru.com/wp-content/uploads/2012/05/CAT-HEADPHONES.jpeg'>
</div>
<div>
This cat has been clicked
<p id='number_clicked'>0</p>
times.
</div>
</body>
</html>
The problem lies in the following line:
catGrid.addEventListener('click', catClick('number_clicked'), false);
In that line you are executing catClick('number_clicked') and returning the result of that expression as the 2nd parameter to the addEventListener function.
Two possible solutions are:
//1: Using an anonymous function:
catGrid.addEventListener('click', function() {
catClick('number_clicked')
}, false);
//2: Using bind:
catGrid.addEventListener('click', catClick.bind(this,'number_clicked'), false);

JavaScript simple function doesn't return anything

I' m new to JavaScript and am writing a function which has to calculate circle area. But the problem here is that I don't fully understand the concept of functions. So here is my Html code where i have 2 div elements with specific ID. I want my function to take the innerHTML from the first div and according to the given formula int the function to output the result into the second div. Can you help me cause maybe I make some huge error inhere.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Circle Area</title>
<meta charset="utf-8" />
</head>
<body>
<div id="area">7</div>
<div id="output"></div>
<script type="text/javascript" src="circle-area.js"></script>
</body>
</html>
And here is my Js file
function calcCircleArea(r, formula) {
r = document.getElementById("area").innerHTML;
var formula = Math.PI * (r * r);
return formula;
}
document.getElementById("output").innerHTML = formula;
You have to call the function
function calcCircleArea() {
var r = document.getElementById("area").innerHTML;
var formula = Math.PI * (r * r);
return formula;
}
document.getElementById("output").innerHTML = calcCircleArea();
FIDDLE
You don't need argument in the function as you are not passing any parameters to the function. You need to call the function. Change your javascript to:
function calcCircleArea() {
r = document.getElementById("area").innerHTML;
var formula = Math.PI * (r * r);
return formula;
}
document.getElementById("output").innerHTML = calcCircleArea();
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Circle Area</title>
<meta charset="utf-8" />
<script>
// There is no need to declare argument variables once again
// Besides, it's better to get radius from outside, i.e. from function call
function calcCircleArea(r) {
return Math.PI * (r * r);
}
</script>
</head>
<body>
<div id="area">7</div>
<div id="output"/>
<script>
document.getElementById("output").innerHTML = calcCircleArea(document.getElementById("area").innerHTML);
</script>
</body>
</html>
<html>
<body>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
enter code here
</html>
This is a simple example for use script inside the html file.
It may helps.

Categories

Resources