Javascript: Why is my code alerting to nothing? - javascript

I've written the following:
var pages=["[www.facebook.com] Facebook is cool. ","[www.bbc.co.uk] British broadcasting corporation. "];
function findScoreC2(s){
var scores=[];
var percentageScores=[];
var contentsArray=[];
s=s.toLowerCase();
for(i=0;i<pages.length; i++){
contentsArray=pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "));
var lowerCaseContents=(pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "))).toLowerCase();
scores[i] =(lowerCaseContents.split(s)).length-1
};
percentageScores=(scores[i] / contentsArray[i].length) * 100;
var finalArray=[];
for(i=0;i<percentageScores.length;i++){
finalArray.push("{score:"+percentageScores[i]+",index:"+i+"}")
};
alert(finalArray);
}
findScoreC2("facebook");
however, alert(finalArray) alerts to nothing (ie an alert box comes up but it says nothing) when it should alert "{score:33,index:0},{score:0,index:1}".
Could anyone enlighten me as to why this might be?
Thanks very much

You set percentageScores to a number. You then try to iterate up to its length property, which gives you undefined when you do percentageScores.length, so the for loop never iterates. You then alert with an empty array, whose toString produces the empty string.
You probably want this:
for(i=0;i<pages.length; i++){
contentsArray=pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "));
var lowerCaseContents=(pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "))).toLowerCase();
scores[i] =(lowerCaseContents.split(s)).length-1
percentageScores[i]=(scores[i] / contentsArray[i].length) * 100;
};

Related

string random characters in a for loop

Im having trouble with the following code while trying to make a random password generator. The first two lines seem to be working as intended. I confirmed this with the following:
If I replace the "passwordText = passwordText.concat(character:" with "console.log(character)" it works in the console. Picks a random char from an array and will console log it the desired amount of times.
However, on line 3 I'm trying to concat these random chars into one string. Any ideas? I'm getting a TypeError: Cannot read property 'concat'. All variables are declared.
for (var i = 0; i < inputLength; i++) {
character = finalCriteria[Math.floor(Math.random() * finalCriteria.length)];
passwordText = passwordText.concat(character);
}
passwordText = passwordText.concat(character);
I would appreciate any guidance on this. Many thanks, Steven.
PS. This is my first week with JS, go easy on me! :)
strings don't have a concat method unlike arrays. What you need is +=:
passwordText += character;
Edit: concat not push
Thanks everyone for your help. Below worked. I also give password text a value as mentioned by caTS.
// function to return the password
function generatePassword() {
for (var i = 0; i < charLength; i++) {
passwordText += finalCriteria[Math.floor(Math.random() * finalCriteria.length)];
} return passwordText
}

Declare JavaScript variable only with ' ' marks

I saw one of the masters doing this:
var example = '';
Then later he continued with this:
example += '<div>just a div</div>';
I wanna know if there's any difference from doing this:
var example;
example += '<div>just a div</div>';
I don't really know if by doing the second method I'm doing wrong and I have to code like shown if the first example.
Updated!
Thank you so much for your answers, Ok I got it I need to define my variable to be able to work woth it, but then another question came... This master also is doing this:
var guess;
and then he does:
guess += myfunction( upper );
where myfunction was declared as follows:
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
So, why here is different? Can any of you answer this please?
Thank you!
Second update!
Again Thanks!
I decided to post the whole code the JS master was doing, at this point I don't understand, so probably you'll be able to clear my doubts.
var randomNumber = myFunction( 10 );
var guess;
var attempts = 0;
var answer = false;
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
do{
guess = prompt( "I created a number from 1 till 10, can you guess it?");
attempts += 1;
if( parseInt( guess ) === randomNumber ){
answer = true;
}
}while( ! answer )
document.write( "Took you " + attempts + " attempts to guess the number " + randomNumber);
Please have a look at:
var guess;
and how later is being declared, so why here works perfectly but in my first example I have to put the '' when declaring my variable?
I hope my question is clear enough for you!
Thank you for your time and patient!
When you do:
var example;
example += '<div>just a div</div>';
You end up with:
`"undefined<div>just a div</div>"`
This is because when you don't initialize a variable, it is undefined, which can be converted to a sensible string "undefined" when you try to add it to another string.
When you do:
var guess;
guess += myfunction( upper );
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
You are adding a number to undefined. This results in NaN (not a number) because undefined cannot be converted into a sensible number.
You can check this yourself next time by opening up your browser's developer tools and running the code in the console.
Edit:
When you do:
var guess;
guess = prompt( "I created a number from 1 till 10, can you guess it?");
There's no issue because you are simply assigning a string to the guess variable. In the previous examples you were adding something to a variable, which means if they are different types then JavaScript has to try to do something sensible.
If you don't initialize your variable it has a value of undefined.
In your last example, you are really saying example = undefined + '<div>just a div</div>' and undefined will be converted to a string and output that way. Probably not what you want.
In general it is a good idea to initialize your variables before you use them which is why var example = '' is preferable in this case.
var myvar
myvar += 'asdf'
console.log(myvar) // prints undefinedasdf
var othervar = ''
othervar += 'sdfasdf'
console.log(othervar) // prints sdfasdf
If you don't initialize the variable then it will be undefined
Appending to undefined object doesn't help.
var example = '';
Here you are initializing an empty string to the variable and therefore appending a string to another string will give the desired output of string concatenation.
Output:
"undefined<div>just a div</div>"
"<div>just a div</div>"
Yes there is a difference the first snipet from the master creates a variable example and gives it a default value, the second statement concatinates the value with 'just a div'
.Your code has an error as it is adding a value to a non-existed value as variable example has no default value.

Why am I getting undefined when putting a string of html to the main page using jQuery?

I'm fairly new to JavaScript and jQuery so any other advice you might have please leave in a comment below. I am making a card game to be played on a single screen in javascript.
Inside the div for id playerHand, I use a javascript function to output the hand of the current player's turn. Whenever I output the current player's hand, I get an output in that div like so:
undefined/ 6H / AD / 7H / 5H / 6S / KC / 8C / 10H / AC / 2H / 8S / 2D / 3S
The hand is made of 13 cards(denoted by numbers 2-10 and J, Q, K, A with a letter for hearts, spades, clubs and diamonds). All 13 cards print out to the div correctly but this random undefined thing is unexpected. The JavaScript function used to output this information is below.
JavaScript jQuery function:
function addHand() {
var htmlString;
for(i = 0; i < hands[currentPlayersTurn].handArray.length; i++) {
htmlString += "/ "+ hands[currentPlayersTurn].handArray[i].name +" ";
}
$("#playerHand").html(htmlString);
}
Look here:
var htmlString;
htmlString's initial "value" is undefined.
Then you stringise it via string concatenation, and keep adding to that initial value. It's neither "random" nor "unexpected"; it's what you programmed into the computer.
You probably meant:
var htmlString = "";
so as to begin with the empty string.
Your issues is with var htmlString since you do not initialize it. Though even if you set to empty string your output won't be as you expect because you will then just replace undefined/string/string/string with /string/string/string. A better approach would be to push the list of names into an array and then join them on /.
function addHand() {
var htmlList = [];
for(var i = 0; i < hands[currentPlayersTurn].handArray.length; i++) {
htmlList.push(hands[currentPlayersTurn].handArray[i].name);
}
$("#playerHand").html(htmlList.join(" / "));
}

Obtain numbers from a field and process them

I have a field which obtains it input through a list of links associated with numbers. (Similar to a calculator but without operators). I want to retrieve these numbers and put them through a function which divides them by 12. (A conversion from feet to inches).
First I have a list of jQuery click functions like this:
$('#a0').click(function(){
writeInput(input, one); // var one = 1;
});
Next I have the function "write Input" (This is where the numbers are displayed on a "screen")
function writeInput(field, str){
$input = $(field);
var text = $input.val($input.val() + str);
$input.text(text);
convert(text);
}
And lastly I have a function which is supposed to divide the number inputted by 12
function convert(input){
var divide = (input / 12);
$("#output").html(divide); //output is a paragraph where the number is displayed
}
When I run my code I am getting NAN output where the number should be. I have tried parseInt() and other tricks. But the closest I have come to something correct is when I got [object] [object] output.
Any help would be appreciated. Thanks!
In your code text is a jQuery object, you are using val as setter which returns a jQuery object, you should use val/text method as a getter for retrieving updated value.
function writeInput(field, str){
var text = $(field).val(function(i, v){
return v + str;
}).text(function(i, t){
return t + str
}).val();
convert(text);
}

Repetition via for loop based on prompt output

So essentially what I'm trying to do is to figure out how to repeat a line x number of times based on a prompt's output.
i.e
<script>
var favnumber = Number(prompt("What is your favorite number?"))
for(var i=0;i<favnumber;i++){
System.out.println(name + "is bad at javascript");
}
</script>
any idea whats wrong?
JavaScript is not Java. So there is no function System.out.println() unless you define it.
To output you hav either to user the DOM, console or alert.
The later might look like this:
<script>
var favnumber = Number(prompt("What is your favorite number?"));
var name = 'Bob';
for(var i=0;i<favnumber;i++){
alert(name + " is bad at javascript");
}
</script>
Besides, try to get used to end every command with ;. Otherwise you run into many weird problems as a JavaScript beginner - and later as well.
JavaScript is not Java, so System.out.println doesn't have any special meaning. You have two options here: to use console.log(), or to use document.write().
I recommend you use console.log(), as it doesn't mess with the current page's HTML structure:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
console.log(name + ' is not Java');
}​
You'll need to open up your browser's JavaScript console to see those messages.
Using document.write() is a bit more cumbersome:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
document.write(name + ' is not Java');
document.write('<br />');
}​
Demo: http://jsfiddle.net/HC3Y2/

Categories

Resources