Error in declaring array JavaScript? - javascript

Working through an intro JS coursera course. I'm making a simple color guessing game. I've inserted a few alerts at the beginning for troubleshooting, but I can't get this program to get reach the alert("test1"); line in my playGame, which is loading immediately through the body element. Any ideas what I'm doing wrong? I seem to be declaring it just fine...
<!DOCTYPE html>
<html>
<body onload="playGame()">
<p>Welcome to my color guessing game</p>
<script language = "JavaScript">
function inArray(needle, haystack){
for (var i = 0; i <haystack.length(); i++){
if (needle === haystack[i]){
return true;
}
}
return false;
}
function changeBackground(color){
document.body.style.background = color;
}
function playGame(){
var correct = false;
alert("Correct status is: " + correct);
var colorArray = ["cyan", "gold", "green", "gray", "magenta", "blue", "red", "orange", "yellow", "white"];
alert("test1");
for (var i = 0; i < colorArray.length(); i++){
alert("for " + i + " the color is " + colorArray[i]);
}
colorArray = colorArray.sort();
alert("answer index is " + answerIndex);
alert("color array length is " + colorArray.length());
var answerIndex = Math.floor(Math.random()*colorArray.length());
alert("the resulting color from the color array is: " + answerColor);
var answerColor = colorArray[answerIndex];
alert("The correct color is " + answerColor);
var answerList = colorArray.join(", ");
var guessCount = 0;
while(!correct){
var colorGuess = prompt("Welcome to my guessing game! The colors available for your choosing are: " + "\n\n" + answerList + "\n\n" + "Which color am I thinking of?");
guessCount++;
if (!inArray(colorGuess, colorArray)){
alert("Your guess wasn't one of the selections that was available or I otherwise don't recognize it." + "\n\n" + "Please try again!");
}
else{
if (colorArray.indexOf(colorGuess)<color.indexOf(answerColor)){
alert("Your guess was alphabetically before the correct color! Try again.");
}
else if (colorARray.indexOf(colorguess)>color.indexOf(answerColor)){
alert("Your guess was alphabetically after the correct color! Try again.");
}
else{
alert("Your guess is correct!");
correct = true;
changeBackground(answerColor);
}
}
}
alert("Great job!" + "\n\n" + "You took " + guessCount + " guesses to get the correct answer!");
}
</script>
</body>
</html>

I've just tested your code.
alert("answer index is " + answerIndex);
alert("color array length is " + colorArray.length());
var answerIndex = Math.floor(Math.random()*colorArray.length());
alert("the resulting color from the color array is: " + answerColor);
var answerColor = colorArray[answerIndex];
alert("The correct color is " + answerColor);
Here you're trying to alert the variable answerIndex, before you declare it.

In JS length is a property which returns the number of elements in an array. MDN Array Length.
In colorArray.length() replace length() by length.

Related

Display corresponding parallel array value to html

I currently have two arrays, nameArray and markArray which are added to when users input their name and mark. I want to display all names and marks at the click of a button but have what mark belongs to who obvious. My attempts are below creating displayInfo but whenever I try to output it to HTML it only shows the last one in each array.
if (Array.isArray(nameArray) && nameArray.length) {
console.log("display all working");
// var displayName = nameArray.toString();
// var displayMark = markArray.toString();
for(let i=0; i < nameArray.length; i++){
var displayInfo = "";
//var displayInfo = nameArray[i] + "<br/>" + markArray[i];
//console.log(displayInfo)
//document.getElementById("result").innerHTML = displayInfo;
displayInfo += nameArray[i] + "<br/>" + markArray[i] + "";
}
document.getElementById("result").innerHTML = displayInfo
}else{
document.getElementById("result").innerHTML = "No result's have been entered! Please enter results before display them!"
}
} ```
var name = document.getElementById("name").value;
var mark = document.getElementById("mark").value;
if(name == "" || mark == ""){
document.getElementById("result").innerHTML = "An input field is empty please try again."
}else{
nameArray.push(name);
markArray.push(mark);
console.log(nameArray);
document.getElementById("result").innerHTML = name + "'s " + "results have been added to the system!"
}
}```
The output should look something like John-4 Jack-6, just any way in which it is clear whos result it is.
if (Array.isArray(nameArray) && nameArray.length) {
console.log("display all working");
var displayInfo = [];
// var displayName = nameArray.toString();
// var displayMark = markArray.toString();
for(let i=0; i < nameArray.length; i++){
//var displayInfo = nameArray[i] + "<br/>" + markArray[i];
//console.log(displayInfo)
//document.getElementById("result").innerHTML = displayInfo;
displayInfo.push(nameArray[i] + "<br/>" + markArray[i] + "");
}
displayInfo.forEach(single => {
document.getElementById("result").innerHTML = single;
})
}else{
document.getElementById("result").innerHTML = "No result's have been entered! Please enter results before display them!"
}
You are overwriting your variable inside your loop until the loop ends, which is why you get the last element of the array. Try my code.

Problems with University code on JavaScript

I'm currently attempting to complete my university coursework but I'm struggling to get my code to work. Can someone give me a helping hand?
Now update your program so that the work of checking the lottery
result is done by a function called checkNumbers(). This function
should take the customer number and the array of winning numbers as
arguments. The customer number should be returned from a function
called getCustomerNumber(). The array of winning numbers should be
returned from a function called getWinningNumbers(). The display of
the results should be done by a function called displayResult(). The
whole process should be kicked off by a function called init().
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="lottotask5.js">
</script>
<meta charset="utf-8">
<title>DCSIS JavaScript Module TMA</title>
</head>
<body>
</body>
</html>
function init() {
new checkNumbers();
new displayResult();
new getWinningNumbers();
new getCustomerNumbers();
}
function getWinningNumbers(){
var winningNumbers = [12,17,24,37,38,43];
return winningNumbers;
}
function getCustomerNumbers(){
var customerNumbers = 12;
return customerNumbers;
}
function checkNumbers(customerNumbers, winningNumbers){
match == false;
for ( var i = 0; i < this.winningNumbers.length; i++){
if (this.customerNumbers == this.winningNumbers[i]){
match == true;
}
}
return match;
}
function displayResult(){
if(match == true){
alert("This Week's Winning Numbers are:\n\n" + winningNumbers[0]
+", "+ winningNumbers[1] +", "+
winningNumbers[2] +", "+ winningNumbers[3] +", "+
winningNumbers[4] +", "+ winningNumbers[5] +
"\n\n The Customer's Number is:\n\n" + customerNumbers + "\n\n
We have a match and a winner!");
}
else
{
alert("This Week's Winning Numbers are:\n\n" + winningNumbers[0]
+", "+ winningNumbers[1] +", "+
winningNumbers[2] +", "+ winningNumbers[3] +", "+
winningNumbers[4] +", "+ winningNumbers[5] +
"\n\n The Customer's Number is:\n\n" + 13 + "\n\n Sorry you are
not a winner this week.");
}
}
Function displayResults cannot see members of array winningNumbers. You have to call function getWinningNumbers() from displayResult() to obtain a list of winning numbers. Same goes for customernumbers and all variables that are not global.
https://www.w3schools.com/js/js_scope.asp

How to change color of the appending element?

I created a "custom append" function that taking in two parameters and appending their's value in a one line.
I need to make the first parameter's value to append in a gray color but the second value have to stay as it is.
I tried to use a "css(property, name)" function but it didn't work.
Where is my fallacy and how to get a needed result?
var showText = function(who, str) {
if (str !== "") {
var colorWho = who.name;
colorWho.css("color", "gray");
$("#storyBoard").append("<br>" + colorWho + ": " + str + "<br>");
var element = document.getElementById("storyBoard");
element.scrollTop = element.scrollHeight;
}
};
Here you go
Fiddle
CSS
p > span { /* If you're going to take this to a larger environment, you may want to use classes instead */
color:gray;
}
JS
var showText = function(who, str) {
if(str !== ""){
var colorWho = who.name;
$("#storyBoard").append("<p><span>"+colorWho + "</span>: " +str+ "<p>");
}
};
var obj = {
name : "Preacher",
}
showText(obj, "Is an awesome comic book !");
Is this what you require?
$("#storyBoard").append("<br><span style='color:gray;'>" + colorWho + "</span>: " + str + "<br>");

Random number generator and if then statements

This code is supposed prompt for two player names and generate a random number between 1 and 6 for each player. It is then supposed to compare those two numbers and provide the output of which player has the higher number or display tie if there is a tie. Sometimes this works and sometimes it does the opposite other times it says both numbers match when they don't.
Anyone have any ideas for me?
var playerOne = " "
var playerTwo = " "
var rollWinner = " "
var p1number = 0;
var p2number = 0;
var end = " "
main()
function main()
{
do {
getNames()
rollDice()
displayResults()
endProgram()
}
while (end == "yes")
}
function getNames()
{
playerOne = prompt("Please enter the name of Player One: ")
playerTwo = prompt("Please enter the name of Player Two: ")
}
function rollDice()
{
p1Number = Math.floor((Math.random()*6)+1)
p2Number = Math.floor((Math.random()*6)+1)
if (p1Number > p2Number)
{
return playerOne
}
else if (p1Number < p2Number)
{
return playerTwo
}
else
{
return "Sorry no winner, there was a tie"
}
}
function displayResults()
{
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
window.alert("The winner is! " + rollDice())
}
function endProgram()
{
end = prompt("Do you want to play again? Enter yes or no")
if (end == "no")
window.alert("Thank you for playing");
else if (end == "yes")
return end;
}
window.alert("The winner is! " + rollDice())
This line calls rollDice again for a 2nd time. You display the results of the first call then you re-roll and display the return value of the 2nd call (which may be different).
// display p1Number and p2Number from first roll
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
// recall rollDice
window.alert("The winner is! " + rollDice())
In displayResults(), you are showing the values of p1Number and p2Number before assigning values to them (since that happens within rollDice()).
So your program is working, but your diagnostic output is misleading you.

How to search for a character in a string and output the index of every place that character appears? (Javascript)

I figured it out, thank you. I need to move the body to the html. Changed some tags in the body section.
}
else
{
window.alert ("You entered an invalid character (" + enterLetter + ") please re-enter");
secondPrompt();
}
}
</script>
<body onload = "firstPrompt();">
<h2>
Word Checker
</h2>
</body>
</html>
You can increment indexOf each time you find a match-
function indexFind(string, charac){
var i= 0, found= [];
while((i= string.indexOf(charac, i))!= -1) found.push(i++);
return found;
}
indexFind('It\'s more like it is today, than it ever was before','o');
/* returned value: (Array)
6,22,48
*/
Using indexOf recursively:
function findMatches(str, char) {
var i = 0,
ret = [];
while ((i = str.indexOf(char, i)) !== -1) {
ret.push(i);
i += char.length; //can use i++ too if char is always 1 character
};
return ret;
}
Usage in your code:
var matches = findMatches(enterWord, enterLetter);
if (!matches.length) { //no matches
document.write ("String '" + enterWord + "' does not contain the letter '" + enterLetter + ".<br />");
} else {
for (var i = 0; i < matches.length; i++) {
document.write ("String '" + enterWord + "' contains the letter '" + enterLetter + "' at position " + matches[i] + ".<br />");
}
}
Live Demo
Full source (with some tweaks from your last question)

Categories