JS for Kids Hangman game - javascript

I don't know what the [i] in answerArray[i] does/means. If someone could explain what it does it would mean a lot. This code came from the book "JavaScript for kids" and I'm trying to get started with just any kind of coding
var words = [
"money",
"pillow",
"maracas"
];
var word = words[Math.floor(Math.random() * words.length)];
var answerArray = [];
Here
for (var i = 0; i < word.length; i++) {
*answerArray[i] = "_";*
}
var remainingLetters = word.length;
while (remainingLetters > 0) {
alert(answerArray.join(" "));
var guess = prompt("Guess a letter, or click cancel to stop playing.");
if (guess === null) {
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
And here
*for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;*
remainingLetters--;
}
}
}
}
alert(answerArray.join(" "));
alert("Good job! The answer was " + word);

Here's an example
https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for_ex
The letters i or j or litterally anything put in that slot when you write for (i = 0; i < 5; i++) represents the current itteration. This is thing called a for loop and you should definitely get to know it if you are just getting started with javascript.
The letter, in short, represents the current itteration of the loop.
for (i = 0; i < 5; i++) { }
What this loop is saying is first i = 0. the variable "i" is 0. Then it says i < 5. This part is the "test". If the test passes, the loop with run again. Then it says i++. This is something that happens after the loop has been run. In this example it increases i with 1.
What happens inside { } will occure 5 times, and the letter i will increase in value, representing the "current loop".
In the demo i linked, you see that the sentence "The number is x" appears in increasing order, starting with 0.
The loop essentially means "While i is less than 5, do this" and the i increases in value each loop and the test inside () is rerun.
In arrays, each slot is represented by a number. MyArray[1] refers to the second item in the array.
If you have an array like this var myArray = ["fi", "fa", "fo"] then you can write console.log[2] to print the third item.
Lets combine this knowledge like this!
var myArray = ["fi", "fa", "fo"];
for (i = 0; i < 3; i++) {
alert(myArray[i]);
}
The for-loop is run 3 times, and each time it is run, i has a bigger value. This lets us refer to every item in the array. A better loop to write would be for(var i = 0; i < myArray.length; i++. This makes us compare i to the size of your array, so the array can be any size it wants to be

1 > the answer array initially empty array=[];
2 > then words[Math.floor(Math.random() * words.length)] this will return a
random string from words array .
3 > then the for loop is just counting the number of characters present in the
selected word and that same time number of _ is inserted in answers Array
4 > then this will just joining all the underscores and make a single string (with in the spaces).
eg -> word "pillow" is selected
then answers Array= ['_','_','_','_','_','_']
then answerArray= "_ _ _ _ _ _" ( Join with spaces).
Thanks.

Related

Adding method to prototype string but want does this method mean

I am trying to understand what this mean?
What I am thinking is that phrase will pass a part of array, so this in this case eve to phrase.palindrome method. That method will take and run it through. First var len takes eve and remove 1 from it using length -1. This results in var len being assigned number two as the length of eve is 3. Now for is in use, so var i = 0; i <= len/2; i++.
now becomes var i = 1;1 <= 1; i++."is this correct"
I don't understand what going on here:
for (var i = 0; i <= len/2; i++) {
if (this.charAt(i) !== this.charAt(len-i)) {
return false;
Here is all of the the code:
String.prototype.palindrome = function() {
var len = this.length-1;
for (var i = 0; i <= len/2; i++) {
if (this.charAt(i) !== this.charAt(len-i)) {
return false;
}
}
return true;
};
var phrases = ["eve", "kayak", "mom", "wow", "Not a palindrome"];
for (var i = 0; i < phrases.length; i++) {
var phrase = phrases[i];
if (phrase.palindrome()) {
console.log("'" + phrase + "' is a palindrome");
} else {
console.log("'" + phrase + "' is NOT a palindrome");
}
}
The code is essentially iterating through the string from both directions, comparing the first and last characters (indexes 0 and len) then the second from first and second from last and so forth until you reach the middle. A word is a palindrome if and only if the first and last characters are the same and the second and second to last characters are the same and so forth.
Note, there is something very wrong with this code. While it is technically possible to mutate the prototypes of built-in types in Javascript you should never, ever, ever do it. You gain no functionality you wouldn't from a normal function, while badly violating the principle of least surprise. Treat all types from other libraries, including built ins as if they are closed for modification and open for extension.
I think this line has error:
for (var i = 0; i <= len/2; i++) {
Beacuse somethimes length can be 3,5,7... and that can be problem.
I added some using examples:
for (var i = 0; i <= Math.floor(len / 2); i++) {
// That same thing with floor in positive numbers, but in negative numbers that works like ceil.
for (var i = 0; i <= ~~(len / 2); i++) {
// That same thing with floor, we can think like this pollyfill of floor.
for (var i = 0; i <= ~~(len / 2) + (Math.abs(len)>len?-1:0); i++) {

Print Prime Numbers (2,3,5,7)

I found the code for solving this problem, but I cannot figure out the logic of the solution.
let n = 10;
nextPrime:
for (let i = 2; i <= n; i++) {
for (let j = 2; j < i; j++) {
if (i % j == 0) continue nextPrime;
}
alert( i );
}
I can't understand how the second for works, if it has an increment like the first, then the result should have been all numbers from 2 to 10, since the beginning of both for is the same number (2) ..
Can you please explain each iteration, for example why 4 is not displayed?
It’s using label to break the inner loop when it finds number is not prime . Outer loop is iterating the number and inner loop checks if it’s divisible between 2 to number.
Label break
the continue nextPrime used for just continue in the loop to the next iteration without finish all the code inside the loop.
like:
data:
for (let i = 1; i <= 3; i++) {
if(i === 2)
continue data;
console.log(i)
}
here when I get to I equal to 2 the code continue to the next number without continue to the rest of the code

Array.pop() not returning all letters in reversing function

I'm currently practising on Codewars, and I've come across a strange issue using the .pop() method. While attempting to reverse the letters in each word in a given string, while maintaining each words position and each space, I am attempting to use a nested for loop to access each letter in each word separately, and pop the last letter off of each word after splitting the words into separate arrays. Here is my code:
function reverseWords(str) {
let val = ''
let newStr = str.split(/(\s+)/)
for(let i = 0; i < newStr.length; i++){
let pieces = newStr[i].split('');
for(let j = 0; j < pieces.length; j++){
val += pieces.pop()
}
}
return val
}
When I do this, I am losing a certain number of letters in each word, and I'm not sure why. For example, when given the string 'The quick brown fox jumps over the lazy dog.' I return 'eh kci nwo xo spm re eh yz .g' I can't seem to wrap my head around why pop is missing the final letter or letters in each word.
I have also tried
function reverseWords(str) {
let val = ''
let newStr = str.split(/(\s+)/)
for(let i = 0; i < newStr.length; i++){
for(let j = 0; j < newStr[i].length; j++){
val += newStr[i].split('').pop()
}
}
return val
}
but this only returns the final letter of each word * the length of the word.
You're mutating the array by .popping it while you're iterating over it. So, for example, if the array originally contains 4 elements, then in the following code:
for(let j = 0; j < pieces.length; j++){
val += pieces.pop()
}
This is what happens:
j starts at 0
you remove the last element from the array (array now contains 3 elements)
j is incremented to 1
you remove the last element from the array (array now contains 2 elements)
j is incremented to 2
Loop ends (because j < pieces.length -> 2 < 2 condition fails)
The words that were originally at positions 0 and 1 do not get popped and concatenated with val.
Change the condition to while (pieces.length):
function reverseWords(str) {
let val = ''
let newStr = str.split(/(\s+)/)
for(let i = 0; i < newStr.length; i++){
let pieces = newStr[i].split('');
while (pieces.length) {
val += pieces.pop()
}
}
return val
}
console.log(reverseWords('The quick brown fox jumps over the lazy dog.'));
Or, much more concisely, use a regular expression to match word characters, and have a replacer function .reverse() them:
const reverseWords = str => str.replace(
/\w+/g,
word => [...word].reverse().join('')
);
console.log(reverseWords('The quick brown fox jumps over the lazy dog.'));
(not sure if you want the . to be reversed with the words or not)

How come it doesn't slice a number until the end despite including the number's length

I made a code to extract every odd numbers from one number, and it works for numbers that are not too long such as "1341" (which give me the numbers "1,13,1341,341,41,1") but oddly doesn't work for very long numbers.
function solve(s) {
var newarray = [];
for (var i = 0; i <= s.length; i++) {
for (var j = 0; j <= s.length; j++) {
var slicing = s.slice(i, j);
if (slicing % 2 !== 0) {
newarray.push(slicing);
}
}
}
return newarray.length;
}
Despite putting s.length, it slices until a certain point. For example:
With "93711892377292643581488317", it slices until "9371189237729", then when it starts from 3 it slices until "93711892377292643" (until the next odd number)
With "65266112954758467", from the start it slices until "6526611295475", then when it starts from 5, it slices until "65266112954758467" (until the next odd number).
What's going on?
slicing % 2 doesn't work properly when slicing is large. Javascript treats large numbers as floating-point numbers, which means it's not accurate to know the value to the nearest integer - in binary, the units bit becomes 0, so it's a multiple of 2.
You want to count all odd numeric substrings within a numeric string.
First, consult the documentation of str.slice(beginIndex[, endIndex]).
Then, in order to gain a better understanding of your code, it is helpful to slowly iterate through a few steps of your loops and write down the expected vs. the observed output.
I recommend to use the debugger built into all modern browsers:
Add a debugger; statement into the inner for-loop:
function solve(s) {
var newarray = [];
for (var i = 0; i <= s.length; i++) {
for (var j = 0; j <= s.length; j++) {
var slicing = s.slice(i, j);
debugger; // <-- we want to break here and check our values
if (slicing % 2 !== 0) {
newarray.push(slicing);
}
}
}
return newarray.length;
}
Press [F12] and run this code in your browser's console for some exemplary input.
The debugger tab should now pop up. Press [F8] to step through your code and keep track of the value of your slicing variable.
You will probably notice that slicing is empty at the beginning. You should start your inner loop from j = i + 1 to fix that.
Also, you might notice that your i iterates one time too many, so that slicing is empty during the final iterations of the inner for-loop. You need to terminate your outer loop one step earlier.
Then, for the problematic input "93711892377292643581488317" you will notice that large numeric slices such as "93711892377292643" will not be recognized as odd. "93711892377292643" % 2 evaluates to 0 instead of 1. In order to understand this, you need to know that JavaScript numbers are internally represented as limited precision floating point values. If you put 93711892377292643 into your browser console, it will evaluate to 93711892377292640 - an even number! JavaScript can only handle integer numbers up to Number.MAX_SAFE_INTEGER == 9007199254740991 without introducing such truncation errors.
Now, how to solve this issue? Well, a number is odd if and only if the last digit is odd. So we don't have to inspect the full number, just the last digit:
function solve(s) {
var newarray = [];
for (var i = 0; i < s.length; i++) {
for (var j = i; j < s.length; j++) {
var digit = s.slice(j, j + 1);
if (digit % 2 !== 0) {
var slicing = s.slice(i, j + 1);
newarray.push(slicing);
}
}
}
return newarray.length;
}
console.log(solve("1234567890")); // 25
Once you have sufficient understanding of this code, you could start improving it. You could for example replace the newarray with a simple counter, as you are only interested in the number of off digits, not the digits themselves.
A faster solution could be written down as follows:
function solve(str) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] % 2) count += i + 1;
}
return count;
}
console.log(solve("1234567890")); // 25
Or, written in a more declarative way:
const solve = (str) =>
str.split('').reduce((count, chr, i) => chr % 2 ? count + i + 1 : count, 0);
console.log(solve("1234567890")); // 25

Why does my code always end with undefined?

I wrote this JavaScript code, but it always ends **undefined**mycode? What have I done wrong/ how can I prevent this in the future. I am running my code through the chrome javascript console.
Here is my code
//Reverse a string
//-------------------------//
//Input a string
var string = prompt("Please enter string");
//console.log(string);
//Find length of string
var stringLength = string.length;
//console.log(stringLength);
//Creating an empty string for outputting answer
var reversedString = "";
//Start from length of the string and work backwards, inputting letter 1 at a time.
for (var i = stringLength; i >= 0; i--){
reversedString += string[i];
//console.log(string[i]);
}
//Outputting the reversed string;
alert(reversedString);
Thanks for any answers in advance
Change your loop from
for (var i = stringLength; i >= 0; i--){
to
for (var i = stringLength-1; i >= 0; i--){
The problem is, the array indices in javascript are 0 based.
Lets say the string entered in the prompt is "abc", the length of the string is 3. In the loop, you access it as string[3] which is undefined. Hence the error.
Here is the fiddle demonstrating the updated code:
http://jsfiddle.net/rf1vmyzg/
adding string[i] is the last thing this code does before alerting you, so therefore the last string[i], (first element in your array, I assume) has the value of undefined.
for (var i = stringLength; i >= 0; i--){
reversedString += string[i];
//console.log(string[i]);
}
I do not know on the top of my head why this is, but I know that it is always a good idea to stick to conventions, and the one for for loops is:
for(var i = 0; i < [length variable];i++) {
...
}
Right code
for (var i = stringLength-1; i >= 0; i--){
reversedString += string[i];
console.log(string[i]);
}
You should not do string[i] instead do string.charAt(i); Also change stringLength to stringLength - 1. That should fix your problem. If you want this to work across different browsers use charAt notation. Javascript arrays start at 0 not 1 that is why you do length - 1 to get the last element. For example:
for a 10 element array indexes are 0-9. 10 is outside the boundaries of the array.
for (var i = (stringLength - 1); i >= 0; i--){
reversedString += string.charAt(i);
This is the correct answer.

Categories