Need Explaination in this word guessing javascript - javascript

So, I want to check wether the input that I give is being correctly executed, but why does the if statement always return false even i give the correct input?
I don't want the solution only the need explanation. Please is there anyone who could explain? I've included my html input elements Just in case something wrong with it.
<script>
var text1 = ["O","K","E"];
var text2 = ["_","_","_"];
function guess(j){
for(i=0; i < text1.length; i++){
if(j == text1[i]){
text2[i] = j;
console.log(text2[i])
}
else {
console.log("try again")
}
}
}
</script>

The comment of #Unglückspilz in code:
// extra "K" to show how to handle multiple finds
var text1 = ["O","K","E","K"];
var text2 = ["_","_","_","_"];
function guess(j){
// a flag to set if one or more letters were found
found = false;
// check every letter in the haystack against given needle
for(i=0; i < text1.length; i++){
if(j == text1[i]){
// exchange underbar against found letter(s)
text2[i] = j;
console.log(text2[i]);
// set flag to true
found = true;
}
}
// no letter was correct
if(!found){
console.log("try again");
}
// return boolean if anything was found (but not how many)
return found;
}

Related

alert() window appears for every element in an array when looping?

I am trying to make some kind of search function, where a pop-up would appear and ask for an input from the customer and then compare it to the array items and return another alert window with either "found" or "not found"
Here is my code for the specific function:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.prompt("found");
} else {
window.prompt("not found");
}
}
}
It is kind of working. The problem is that it keeps showing a new alert window for every single element in the array. For example if I have 6 elements in the array and only one is matching the search input, then it will show me 5 alert windows with "not found" and one with "found". Another one appears after i close the previous one or if I click the ok button. How do I make it show me the alert window only once to tell me if it found it or not? Thanks!
Put the alert (not prompt) after the loop. Also need to switch to using a variable to track whether or not the item was found:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
break;
}
}
window.alert(found ? 'found' : 'not found');
}
Instead of showing the alert every time, set a variable such as var found=true. After loop terminates then show alert based on status of that var.
To show alert only once you have to execute the alert after loop ends, not inside loop.
Since you aren't doing anything else in your function after the loop, you can simply return when you find the element you were looking for. And only display the "not found" if you finish the loop without finding the element.
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.alert("found");
return;
}
}
window.alert("not found");
}
You could also simplify this by using Array.prototype.indexOf or Array.prototype.includes
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
}
}
if(found == true)
window.prompt("found");
else
window.prompt("not found")
}
you are telling it to show the message every time it finds one, if you are seeking to finding only 1 match then just terminate the loop when you find it.
End the loop using break; or simply just set i to the arrays length:
......
if (model.items[i] == searchInput) {
window.prompt("found");
return 0;
}
.....
window.prompt("Not found"); //if fucntion doesn't return then it's not found.
OR
var found = false;
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
break;
}
.....
if(!found) window.prompt("Not found");
OR
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
i = items.length;
}
.....
if(!found) window.prompt("Not found");

what is the order of boolean logic in Javascript?

I wanted to use two Not and one and in booleans to test if the variable is neither upper case nor lower case.
I used this code so far but it didn't work as required:
else if ((x[i]) !== (x[i].toUpperCase()) && (x[i]!== x[i].toLowerCase()) ){
x.splice(x[i], 1);
}
This code was for a function that sorts entered strings yet uppercase are sorted first.
Here is the full code, I am also open to understanding better ways to create this function apart from boolean logic and the array methods I used.
function alpha(str){ // United States
var x = str.split(""); // [U,n,i,t,e,d,S,t,a,t,e,s]
var cap = [];
var small = [];
for (var i = 0; i<x.length; i++){
if (x[i] == x[i].toUpperCase()){
cap.push(x[i]);
}
else if ((x[i]) !== (x[i].toUpperCase()) && (x[i]!== x[i].toUpperCase()) ) {
x.splice(x[i], 1);
}
else {small.push(x[i]);}
}
var z = cap.sort();
var y = small.sort();
return z.concat(y).join("");
}
Please note the second else if statement is only useful because the code adds an empty space string at the beginning of the output, I'm not sure where it comes from, so please let me know if you have any idea how to sort this even without using the second else if.
In the ASCII table, upper case letters come first. That's why they come first when you sort alphabetically. Here's a link to a page on Wikipedia that shows the table with the upper case letters appearing first and their numerical equivalents. It's even printable.
Also, I took the liberty of simplifying your code a little. Seems like .splice() was not necessary.
function alpha( str ) {
var x = str.split(""); // [U,n,i,t,e,d,S,t,a,t,e,s]
var cap = [];
var small = [];
var length = x.length;
for (var i = 0; i < length; i++) {
if (x[i] === x[i].toUpperCase()) {
cap.push(x[i]);
} else if (x[i] === x[i].toLowerCase()) {
small.push(x[i]);
}
}
return cap.sort().concat(small.sort()).join("");
}
Maybe explain what you're trying to do? It most likely has been done before in some form and you definitely came to the right place to find an answer.
Is this what you want to do?
var str = "United States";
function alpha(str) {
return str.split('').sort().join('');
}
alert(alpha(str));
In all programming languages (as far as i know), boolean expressions are always evaluated from the left to the right with brackets of course.
So in the following example my_func() is called first, and then if there is the chance that the complete expression becomes true my_other_func() is called
if (my_func() && my_other_func()) {
// I only get here if my_func() AND my_other_func() return true
// If my_func() returns false, my_other_func() is never called
}
The same is true for the "or" operator in the following example
if (my_func() || my_other_func()) {
// I only get here if my_func() OR my_other_func() return true
// If my_func() returns true, my_other_func() is not called
}
So back to your code, in details this part (I reformated it a bit for better readability):
if (x[i] == x[i].toUpperCase()){
// only uppercase here
cap.push(x[i]);
} else if (x[i] !== x[i].toUpperCase() && x[i] !== x[i].toUpperCase()) {
// tested twice the same thing, so Im really sure that its not uppercase :D
// only lowercase here
x.splice(x[i], 1);
} else {
// I will never reach this
small.push(x[i]);
}
Im not sure what you want to do, but I hope the comments help to understand your code.

How to get the position of a typed letter in a textarea with Javascript?

I am creating a dropdown while typing in a textarea. How can I get the position of the typed letter given a keyup event?
Greg's answer seems to work. But if you want a more simpler way to get it, you can access the selectionStart property of the textarea.
For example
var myTextArea = $("#mytextarea");
myTextArea.keyup(function () {
console.log("The last typed character is at: ", myTextArea.get(0).selectionStart - 1);
});
http://jsfiddle.net/wasjdhtu/
var oldValue = '';
var keyup = function() {
var value = document.getElementById('myTextArea').value;
for(var i=0; i<value.length; i++) {
if(i >= oldValue.length) {
// letter typed at end
oldValue = value;
return; // not really necessary since we should be at the end of the loop anyway
} else if(value.charAt(i) !== oldValue.charAt(i)) {
// letter typed at i
oldValue = value;
return; // no need to keep searching
}
}
// no new letters typed
}

Loop through array checking for indexOf's more simple?

Okay, like the title says. I have a array looking like this:
var hiTriggers = new Array();
hiTriggers = ["hi", "hai", "hello"];
And I'd like to check through it if it finds either of those. I can already achieve this by doing the following:
if(message.indexOf("hi") >= 0) {
// do whatever here!
}
But I'm looking for an more efficient way rather than doing 100 if() checks. Such as loop through an array with the "hiTriggers".
I tried the following:
for(var i; i < hiTriggers.length; i++) {
console.log(hiTriggers[i]); // simply to know if it checked them through)
if(message.indexOf(hiTriggers[i]) >= 0) {
//do stuff here
}
}
Which sadly did not work as I wanted as it does not check at all.
Thanks in advance and I hope I made sense with my post!
Edit; please note that I have 'messaged' already 'declared' at another place.
It doesn't run because you didn't give the i variable an initial value. It is undefined.
Change to use var i=0;:
for(var i=0; i < hiTriggers.length; i++) {
//console.log(hiTriggers[i]); // simply to know if it checked them through)
if(message.indexOf(hiTriggers[i]) >= 0) {
//do stuff here
console.log("found " + hiTriggers[i]);
}
}
Try using a regular expression to match the message. The \b is a word boundary marker, and the words between the | characters are what is being searched for. If any of the words appear in the message, then message.match will return the array of matches, otherwise null.
var pattern = /\b(Hello|Hi|Hiya)\b/i;
var message = "Hello World";
if (message.match(pattern))
{
console.log("do stuff");
}
You can write even simpler using a for in loop:
for(var v in hiTriggers){
if(message.indexOf(hiTriggers[v]) >= 0) {
//do stuff here
console.log("found " + hiTriggers[v]);
}
}
Problem is becoz - you have not initialized your var i, make it var i = 0;
You can try forEach loop.
hiTriggers.forEach(function(e) {
if(message.indexOf(e) >= 0) {
//do sthg here
}
})

Radio Button Validation: I could validate it but I cant figure out the reason

I was stuck trying to validate if a radiobutton was selected or not and, in consequence, show alerts. Well, I found the mistake (I was putting the conditional statement inside the loop).
Even I solved the problem, I can’t figure out yet why my code works correctly outside the loop but doesn’t work inside it. Now I'm stuck with this.
I appreciate if anyone can tell me what’s the reason.
Below you'll see both JS codes, but here you have the fiddles examples:
JSFiddle that doesn't work
JSFiddle that works
This is the JS code that doesn’t work:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
result = true;
break;
}
if(result === false){
alert('Please, choose an option');
return false;
}else{
alert('You\'ve choosen ' + getNames[i].value)
}
}//Loop ends here.
}
And this is the JS code that works without problems:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
result = true;
break;
}
}//Loop ends here.
if(result === false){
alert('Please, choose an option');
return false;
}else{
alert('You\'ve choosen ' + getNames[i].value)
}
}
Maybe the for loop in JS code that doesn’t work has a wrong logic, it means that if the first radiobutton checked, the for loop stops; if the first radiobutton does not checked, it will alert 'Please, choose an option' and stops the for loop. The logic only validates the first radiobutton. Maybe thats the problem.
It's because of your break; line.
When it's inside the loop you're breaking it out on true before it has a chance to hit the following code: if(result === false)
break is breaking out of the entire loop which means it never hit's your if(result===false)
Hope that helps!
Wrong logic inside the loop, try this:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
alert('You\'ve chosen ' + getNames[i].value)
result = true
}
if (i == getNames.length - 1 && !result)
{
alert('Please, choose an option')
}
}
}
If your question is how do I make it work, there are several good suggestions in the answers.
If you want to know: "Why didn't it work using the first method?" The best answer is that the break; line was causing your loop to terminate immediately, and therefore preventing the alert("You've chosen...") from having the opportunity to trigger.

Categories