After continue statement i dont see any console printing - javascript

I am new to js.After continue statement i dont see any console printing.
I thought continue will move to next number or something else will happencan you guys tell me why its not working.I am providing my code below.
var String = "paa"
//var String = "pak"
var splittedString = String.split()
console.log("outside outer loop");
for(i=0; i<splittedString.length; i++) {
var c = splittedString[i];
console.log("outside inner loop");
for(j=0; j<splittedString.length; j++) {
console.log("inside inner loop");
if( i === j)
{
console.log("inside if condition");
continue;
}
console.log("c ---------->" + c);
console.log("splittedString[j]---------->" + splittedString[j]);
//console.log("inside inner loop");
if( c === splittedString[j] ) {
//else if( c === splittedString[j] ) {
console.log("inside comparison");
console.log("not unique string");
break;
}
else {
console.log("its an unique string")
}
}
}

Your code works "fine". The reason there is no console log is, that you have only one iteration. In that iteration both i and j equalst to 0.
Try console.log(splittedString). You will get your string in an array. I guess what you wanted to do was var splittedString = String.split('') (split it with "empty" character").
Although looping through array of characters is equivalent to looping through string itself. No need to split the string. You can do splittedString = String and the result in this case will be the same as if you split it.
And as others mentioned try to avoid using variable names that could incline variable type (in your case String). Even if the code works, it is harder to read.

Related

Javascript - extract letters from an alphanumerical string via loop

Hello there StackOverflow people,
What I expected:
Removing the numbers of the string "23Ka5X". The loop counts the length and the if statement extracts the letters into an array letterMemory. When no letters are in the string, the message '"oh no numbers!" should be the output.
What I ran into:
I have been working on this for some time now but I can't find my mistake. I don't know if I missed a simple detail or made a big mess.
My feeling and console output:
var letterMemory = [];
function orderMsg(mixedMsg) {
for (var loopString = 0; loopString < mixedMsg.length; loopString++); {
if (isNaN(parseInt(mixedMsg.charAt[loopString]))); {
letterMemory.push(mixedMsg.charAt[loopString]);
return letterMemory;
} if (!isNaN(parseInt(mixedMsg.charAt[loopString]))) {
return "oh no numbers!";
}
}
}
console.log(orderMsg("23Ka5X"));
I feel like the issue is trying to push any letter into the array letterMemory via letterMemory.push(mixedMsg.charAt[loopString])
does not work how I imagine it.
I would be really grateful for your help!
I found a simple solution via .replace() but I really want to make it work with a loop and if statements since loops combined with if statements were my latest freecodecamp lessons and I want to get better at it.
The fixed code
function orderMsg(mixedMsg){
var letterMemory = []
for (var loopString = 0; loopString < mixedMsg.length; loopString++){
if (isNaN(mixedMsg[loopString])){
letterMemory.push(mixedMsg[loopString])
}
}
if (letterMemory.length){
return letterMemory
} else {
return 'oh no numbers!'
}
}
The issue was
The for loop was not executing since you terminated it with ; at the end.
charAt is a function, so you either do string.charAt(index), or you can also simply say string[index].
You are using the return statement within the for loop, so what will happen is even if the for loop ran (without the semi-colon at the end), it would run just once.
One other issue is that the variable letterMemory is declared outside the function so that means if you were to call this function twice, it would use the same letterMemory array.
-end of answer-
Additional read: you can use split, filter and ternary operator to condense the function as follows ..
function orderMsg(mixedMsg){
const letterMemory = mixedMsg.split('').filter(isNaN)
return letterMemory.length ? letterMemory : 'oh no numbers!'
}
This could be helpful,
function orderMsg(mixedMsg) {
for (var loopString = 0; loopString < mixedMsg.length; loopString++) {
if (isNaN(parseInt(mixedMsg.charAt(loopString)))) {
letterMemory.push(mixedMsg.charAt(loopString));
}
}
return letterMemory;
}
var arr = orderMsg("23s5");
if (arr.length == 0) {
console.log("oh no numbers!")
} else {
console.log(arr);
}
Use replace with regex globally, replacing all digits by an empty string:
string.replace(/[0-9]/g, "")
You have terminated for loop in the same line with ;.
charAt() is a method.
Return value after for loop ends.
var letterMemory = [];
function orderMsg(mixedMsg) {
for (var loopString = 0; loopString < mixedMsg.length; loopString++) {
var letter=parseInt(mixedMsg.charAt(loopString));
if(isNaN(letter)){
letterMemory.push(mixedMsg.charAt(loopString));
}
}
if(letterMemory.length>0){
return letterMemory;
}
else{
return "Oh no numbers!";
}
}
console.log(orderMsg("23Ka5X"));
Maybe try using .test to match the letters.
function orderMsg(str){
var result = [];
for(var letter of str){
if(/[a-zA-Z]+/g.test(letter)){
result.push(letter)
}
}
if(result.length === 0){
return 'Oh no numbers'
}
return result
}
For a more thorough explanation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

searching for value in an array with a for loop in javascript

I am searching for an value from an array in javascript and this is my code.
HTML
<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>
Javascript
let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");
chkbutt.addEventListener("click", arraycheck);
function arraycheck () {
for(i=0; i<arr.length; i++) {
if(txtval.value==arr[i]) {
alert("match found for " + txtval.value)
}
else {
alert("its not there")
}
}
}
At the moment, I keep getting alert saying "its not there" when I enter "dog". It prints "its not there" twice and then prints "match found for dog".
I would like the alert to show only if the word does not exist in the array. I know it is doing this because I have the if statement in the for loop and each time if the index of the array does not match, it shows the alert. But how do I do it?
You're alerting on every pass of the loop. Instead, use a flag and alert at the end:
function arraycheck () {
var found = false; // *** The flag
for (var i=0; !found && i<arr.length; i++) {
// ^^^^^^^^^---- *** Stop looping if we find it
if (txtval.value==arr[i]) {
found = true; // *** Set the flag, it was found
}
}
if (found) {
alert("match found for " + txtval.value);
} else {
alert("its not there");
}
}
or we could just use the result of the == directly:
function arraycheck () {
var found = false; // *** The flag
for (var i=0; !found && i<arr.length; i++) {
// ^^^^^^^^^---- *** Stop looping if we find it
found = txtval.value==arr[i]; // *** Set the flag if it was found
}
if (found) {
alert("match found for " + txtval.value);
} else {
alert("its not there");
}
}
(Side note: Unless you're declaring i somewhere you haven't shown, your code is falling prey to The Horror of Implicit Globals [that's a post on my anemic little blog]. Declare your variables. I've added declarations for i in the examples above.)
However, there's already a function for that (two, in fact): includes (on newer JavaScript engines) and indexOf (on older ones):
function arrayCheck() {
var found = arr.includes(txtval.value); // <===
if (found) {
alert("match found for " + txtval.value)
} else {
alert("its not there")
}
}
or the found part of that on older browsers using indexOf:
var found = arr.indexOf(txtval.value) != -1;
In a comment you asked:
I was wondering if you could also stop the loop in my code using "return"?
Yes, that's yet another way to do it in this specific case, since exiting the function (with return) exits the loop:
function arraycheck () {
for (var i=0; i<arr.length; i++) {
if (txtval.value==arr[i]) {
alert("match found for " + txtval.value);
return;
}
}
alert("its not there");
}
You can simplify using indexOf method,
if(arr.indexOf(txtval.value) > -1)
DEMO
let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");
chkbutt.addEventListener("click", arraycheck);
function arraycheck () {
if(arr.indexOf(txtval.value) > -1)
{
alert("match found");
}
else {
alert("its not there");
}
}
<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>
Try the following with Array's includes() in a more simpler and cleaner way:
let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");
chkbutt.addEventListener("click", arraycheck);
function arraycheck () {
if(arr.includes(txtval.value)){
alert("match found for " + txtval.value)
}
else{
alert("its not there")
}
}
<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>
Create a variable that will turn to true when a match is found. Then if after the loop the variable is still false, then no match has been found.
Or better yet, use lodash filter. It simplifies the looping process.
You can try to find the index of your txtval.value in the array by using JavaScript Array indexOf() method.
It takes a input value and output the index number of that value in the Array if the value exists.
As javascript array index starts from 0, so if the value exists, the method will return integer(index in the array) value that is greater than -1.
So, in your case,
function arraycheck () {
var index = arr.indexOf(txtval.value);
if(index > -1){
//alert for found match
}else{
//alert for no match found
}
}

JavaScript - conditional throwing an uncaught syntax error

I am currently working on a challenge to convert any amount of arbitrary numbers entered into the function below as a currency (expressed by a string where every three characters are separated by a comma). All was okay until I realized that if the length of the number entered was 4, then the comma would need to be placed as 1,234 rather than 123,4.
It seems the function has spiralled out of control a little when I wrapped the initial if statement around my for loop. (1) I keep getting thrown an 'Uncaught SyntaxError: Unexpected token else' in the console. (2) I thought it may be due trying to place an if/else around the for/if/else. Any light shed on my error would be much appreciated. Charlie
function toCurrency(price){
var newStrng = price.toString().split("");
var stringCh = [];
if(newStrng.length===4){
console.log("gotcha");
stringCh = newStrng.splice(1,0,",");
return stringCh;
} else {
for(var i = 0; i < newStrng.length; i++) {
if(i %3 === 0 && i !== 0){
stringCh.push(",");
stringCh.push(newStrng[i]);
}
} else {
stringCh.push(newStrng[i]);
}
}
var finallyDone = stringCh.join("");
return finallyDone;
}//EO function
The if statement in the following block
for(var i = 0; i < newStrng.length; i++) {
if(i %3 === 0 && i !== 0){
stringCh.push(",");
stringCh.push(newStrng[i]);
}
} else {
stringCh.push(newStrng[i]);
}
}
has an extra }, right before the else. Take it out and you should no long receive the syntax error.
You can make it easier to spot mistakes like this in the future by ensuring your code is properly indented so you can see which brackets are associated with which blocks. Though I appreciate it could be reasonably indented in the source code and may not have copied across to SO perfectly.
There is a } in the wrong place inside the for loop, that need to be moved after the else block. As it is, the if statement is located in the for loop, but the else block is located outside of the loop, which is not valid syntax.
function toCurrency(price){
var newStrng = price.toString().split("");
var stringCh = [];
if(newStrng.length===4){
console.log("gotcha");
stringCh = newStrng.splice(1,0,",");
return stringCh;
} else {
for(var i = 0; i < newStrng.length; i++) {
if(i %3 === 0 && i !== 0){
stringCh.push(",");
stringCh.push(newStrng[i]);
} else {
stringCh.push(newStrng[i]);
}
}
}
var finallyDone = stringCh.join("");
return finallyDone;
}//EO function
remove } after,
stringCh.push(newStrng[i]);

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
}
})

Error in javascript recursive function

I have the following piece of code (for the present case it may be considered as a function to remove the attributes from a valid html string fed as input):
function parse(htmlStr)
{
console.log(htmlStr);
result+="<"+htmlStr.tagName.toLowerCase()+">";
var nodes=htmlStr.childNodes;
for(i=0;i<nodes.length;i++) {
var node=nodes[i];
if(node.nodeType==3) {
var text=$.trim(node.nodeValue);
if(text!=="") {
result+=text;
}
}
else if(node.nodeType==1) {
result+=parse(node);
}
}
result+="</"+htmlStr.tagName.toLowerCase()+">";
return result;
}
But it is not working as expected. For example, in the following case when I feed it the following html as input:
<div id="t2">
Hi I am
<b>
Test
</b>
</div>
it returns <div>Hi I am<div>Hi I am<b>Test</b></div>.
Also the page crashes if some large input is given to the function.
NOTE: I know there are better implementations of removing attributes from a string using jQuery, but I need to work with the above function here & also the complete code is not for removing attributes, the above is just a shortened part of the code
There is something wrong with your result variable. It is undefined and global. In each recursion you would append the same string to itself, which also makes it crashing for huge inputs. (I can't reproduce anything, it crashes right away with a Undefined variable Error)
BTW: Your argument is no htmlStr, it is a domNode. And you're not parsing anything. Please don't use wrong self-documenting variable names.
Corrected version:
function serialize(domElement) {
var tagname = domElement.tagName.toLowerCase();
var result = "<"+tagname+">";
// ^^^ ^ not a +=
var children = domElement.childNodes;
for (var i=0; i<children.length ;i++) {
// ^^^ was also missing
if (children[i].nodeType == 3) {
result += children[i].data;
} else if (children[i].nodeType == 1) {
result += serialize(children[i]);
// ^^ add a child's result here
}
}
result += "</"+tagname+">";
return result;
}
I would not use trim(), that would produce <div>Hi<b>I</b>am</div> from <div>Hi <b>I</b> am</div>. You might do something like .replace(/\s+/g, " ").
This result+=parse(node); -> In you case you shouldn't merge the result inside recursion like that..
What happens is the return result from <b> recursion call appends the existing result with returned result. Where the existing result is <div>Hi I am and the returned result is <div>Hi I am<b>Test and so at the end of recursion you have <div>Hi I am<div>Hi I am<b>Test.
var result = '';
function parse(htmlStr) {
result += "<" + htmlStr.tagName.toLowerCase() + ">";
var nodes = htmlStr.childNodes;
for (i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.nodeType == 3) {
var text = $.trim(node.nodeValue);
if (text !== "") {
result += text;
}
} else if (node.nodeType == 1) {
parse(node);
}
}
console.log(result);
result += "</" + htmlStr.tagName.toLowerCase() + ">";
return result;
}
Fixed fiddle: http://jsfiddle.net/FBnYT/
Change
result+="<"+htmlStr.tagName.toLowerCase()+">";
to:
var result="<"+htmlStr.tagName.toLowerCase()+">";
WOrks fine in demo: http://jsfiddle.net/qtuUA/
The crash occurs because the loop control variable is not locally scoped. So in addition to the other recommended changes:
for (var i = 0; i < nodes.length; i++)
...

Categories