for loop is not working - javascript

Can someone explain why this for...loop doesn't work? (it should write all checked checkboxes but it writes only the last checked)
function Matula()
{
var x = document.getElementsByTagName("body")[0];
var y = document.createElement("p");
var g = document.createTextNode("Vasa pizza bude obsahovat:");
y.appendChild(g);
x.appendChild(y);
var swag = document.forms["lol"].matej.length;
for (var i = 0; i < swag; i++)
{
if (document.forms["lol"].matej[i].checked)
{
var torko = document.getElementsByTagName("body")[0];
var q = document.createElement("p");
var w = document.createTextNode(document.forms["lol"].matej[i].value);
q.appendChild(w);
torko.appendChild(q);
return mocny = 0
}
};
}

return mocny = 0
exits the function , so for it loops only once, put it outside for loop

There is a return statement in your if block. This will essentially break the loop after the first time it goes inside the if. So that means only value of one check box will be print out.

I have no idea as to what that is supposed to do as it is awfuly confusing will all those var names. But your return inside your if, which inside your for loop, doesn't seem right.
You should put that at the last line of your function.

A cleaner code could look like this:
function Matula() {
var body = document.body;
addParagraph(body, "Vasa pizza bude obsahovat:");
var allToppings = document.forms["lol"].matej;
var toppingsCount = allToppings.length;
for (var i = 0; i < toppingsCount; i++) {
if (allToppings[i].checked) {
addParagraph(body,allToppings[i].value);
}
}
}
function addParagraph(body, textToAdd) {
var p = document.createElement("p");
p.appendChild(textToAdd);
body.appendChild(y);
}
Typed off my head, might contain typos
Makes it so much easier to read. Btw. Bracket position does make a difference (it isn't Java), so keep it on the same line (Google the reasons) Does it work for you?

Related

Why Javascript console.log result is undefined while reversing the string?

var a = "gsdgtrshghf";
function reverseString(strr){
if (!strr.length){
var result="";
for(var i=strr.length;i>0;i++){
var a=strr.chatAt(i);
result+=a;
}
}return result;
}
console.log(reverseString(a))
When I tried to run it it returned me "undefined". I wonder what's the problem here.
The main reason is you are declaring var result="" and returning from outside of if(so it become undefined as its scope is only inside if statement) and other errors areas mention in comments you have a typo, charAt not chatAt. You can also simply use strr[i] to get the char. Also, you should do i-- and i >= 0 if you start at strr.length, otherwise for loop is immediately completed at the condition check. Check the below code.
var a = "gsdgtrshghf";
function reverseString(strr){
var result="";
if (strr.length){
for(var i=strr.length-1;i>=0;i--){
var a=strr.charAt(i);
result+=a;
}
}
return result;
}
console.log(reverseString(a))
Have a look:
var a = "gsdgtrshghf";
function reverseString(strr) {
var result = "";
if (strr.length != null) {
for (var i = strr.length - 1; i >= 0; i--) {
var a = strr.charAt(i);
result += a;
}
}
return result;
}
console.log(reverseString(a));
// Better
const reverse = str => Array.from(str).reverse().join('');
console.log(reverse('foo 𝌆 bar mañana mañana'));
Explanation
It's charAt(i) not chatAt(i)
Loop should start from length - 1 and end at 0 and i should be decremented
And finally declare the variable outside of if
i.e for(var i = strr.length - ; i >= 0; i--){
not for(var i=strr.length;i>0;i++){
Better yet, use combo of Array.from(str).reverse().join(''), as it even works with Unicode characters, as pointed out in comments by gaetanoM

How can i write a function, which if it's parameter is a node collection, executes for all node elements in javascript?

It was very confusing, how to ask this question (especially, with half knowledge of english).
So what i want to do is, to write a function what detects if it's parameter is a single node, or a node collection, and depending on that, it gets the data of the node/nodes. But it's easier to show, than describe. (the explanations are in the comments inside the code) And i want to appologize for language mistakes in english and in javascript too, and the long explanation of my problem.
var e, eH;
function x(y){
e = y;
eH = e.offsetHeight;
};
var ps = document.querySelectorAll("p");
x(ps);
e.style.top = `${eH}px`;
just for an example, i want to set the top style property to the element's height, but the ps is a node collection.
var e, eH, i = 0;
function x(y){
e = y;
eH = e.offsetHeight;
howmany(e)
};
function howmany(z){
e = z;
if (e[i] !== undefined){
for (i; i<e.length; i++){
e = e[i]
}
};
var ps = document.querySelectorAll("p");
x(ps);
e.style.top = `${eH}px`;
that was my first idea, but i know, in this way it will never work
var i,a;
function fun(e){
i = 0;
a = e;
if (e[i] === undefined){
a+=1
}
else{
for (i; i<e.length; i++){
a[i]+=1;
}
}
};
var x = [1,2,3,4,5];
fun(x);
then i tried with numbers, it works. But not solution for my problem.
var e, eH, i = 0;
function x(y, whattodo){
e = y;
eH = e.offsetHeight;
c = whattodo
howmany(e, c)
};
function howmany(z, v){
e = z;
if (e[i] !== undefined){
for (i; i<e.length; i++){
e[i].v
}
};
var ps = document.querySelectorAll("p"),
var wtd = style.top = `${eH}px`;
x(ps, wtd);
if my goal is, to set especially one property on one or multiple elements, this will be great, but it isn't my goal.
my goal is that when i call the function, with a node collection, i can "control" not one element from the collection, and not the collection, but every single element in the collection.
since i think it's impossible to describe my problem this way, let me show a real example. I'll show my code:
var elem, celElem, elemTop, elemMag, elemBot, elemCent, winTop, winMag, winBot, winCent;
function getElem(el, cEl){
elem = el,
celElem = cEl,
elemTop = 0,
elemMag = elem.offsetHeight,
elemBot = elemTop+elemMag,
elemCent = elemTop+(elemMag/2),
winTop = window.pageYOffset,
winMag = window.innerHeight,
winBot = winTop+winMag,
winCent = winTop+(winMag/2),
if (celElem === undefined){celElem = elem};
topMag(elem);
};
function topMag(x){
elem = x;
if (getComputedStyle(elem).position === "fixed"){
elemTop = elem.offsetTop;
}
else{
do{
elemTop += elem.offsetTop;
elem = elem.offsetParent;
}
while(elem != "[object HTMLBodyElement]");
elem = x;
}
};
var targetElem = document.querySelectorAll("p");
var nagyElemCent = -Math.abs((winCent-elemCent)/((elemMag+winMag)/2))+1;
getElem(targetElem);
elem.style.opacity = nagyElemCent;
i hope this example better describes my problem. What i want is, when i set the elem in the last line of code, the elem means all the paragraphs. I have many pre-coded numbers like nagyElemCent, but most of the times them need to be modified to get what i want.
To know whether or not a value is a node or a node collection, you can check to see if it has a length property on it.
Inside of the function, if you check and have received a single node, turn that single node into an array and act on it that way, so you only have to check once if it's an array, and don't have to worry about it for the rest of the function.
function doSomething(nodes) {
if (!('length' in nodes)) {
nodes = [nodes]
}
nodes.forEach(node => {
// do something w/ each node
})
}

Is it possible to have a javascript object without braces?

There is something like this found in my javascript homework. Is this valid, or did they forget to put the braces?
var squares = [],
SIZE = 3,
EMPTY = " ",
score,
moves,
turn = "X";
There are 6 variables being declared in your code. It has nothing to do with an object.
squares is an array, size is a number (3), empty is a string ( ), score and moves are undefined and turn is a string (X)
Google javascript comma operator
EDIT: Declare variables used in scope
var doStuff = function() {
var i,
c = 2,
stuff = "stuff";
};
Rather than:
var doStuff = function() {
//some code
for( var i = 0; i <= 10; i++ ) {
//
}
//some code
var c = 2;
//some code
//some code
var stuff = "stuff";
};
As it lets developers see all the variables that are declared in that scope at a single glance, rather than having to search through the block to see what vars are being declared/used.
They didn't forget. Your teacher just didn't repeat the term 'var' for every variable.
That's the same as:
var squares = [];
var SIZE = 3;
var EMPTY = " ";
var score;
var moves;
var turn = "X";

For loop doesn't show my range

I'm trying to get my for loop to show every number between 47 to 28 in order highest to lowest.
For some reason my code gives me the answer "28, 28".
Can anyone help me se what I've done wrong? I just want to add that I'm still very new to javascript!
var fx = "";
var printRangeReversed = function(rangeStart1,rangeStop1){
for (var a3=rangeStart1; a3 > rangeStop1; a3--);
fx+=a3+",";
return fx=rangeStop1&&(fx+=a3),fx;
return fx = fx.substr(0,fx.length-1);
}
ANSWER = printRangeReversed(47,28);
The for loop ends with a ;, so the subsequent line is just executing as if it were outside the loop. Also, the second return statement is redundant, as the code below the first return is unreachable.
A better code would be
var fx = "";
var printRangeReversed = function(rangeStart1,rangeStop1){
var arr = [];
for (var a3 = rangeStart1; a3 >= rangeStop1; a3--)
arr.push(a3);
return arr.join(); // same as arr.join(",")
}
fx = printRangeReversed(47, 28);
Note, that I've used >= instead of just >, as it isn't what you want.
You don't want to do a return inside the loop. Let it finish, then return the result. For example:
var printRangeReversed = function(rangeStart1,rangeStop1){
var fx = "";
for (var a3=rangeStart1; a3 > rangeStop1; a3--) {
fx+=a3+",";
}
return fx;
}
ANSWER = printRangeReversed(47,28);

Javascript: matching a dynamic string against an array

I'm attempting to teach myself javascript. I chose something I assumed was simple, but ran into problems relatively quickly.
I'm attempting to search a string for another string given by the user.
My code so far is:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = [];
var one = 0;
var two = 0;
var k = 0;
var sourceSearch = function(text) {
for(i = 0; i < source.length; i++) { //for each character in the source
if(source[i] === searchString[0]) { //if a character in source matches the first element in the users input
one = source.indexOf(i); //confused from here on
for(p = searchString.length; p > 0; p--) {
}
}
}
};
sourceSearch(searchString);
My idea was:
check to see if the first loop finds a character that matches the first character in the user input
if it matches, check to see if the next X characters after the first match the next X characters in the source string
if they all match, push them to the hits array
My problem: I have no idea how to iterate along the arrays without nesting quite a few if statements, and even then, that wouldn't be sufficient, considering I want the program to work with any input.
Any ideas would be helpful. Thanks very much in advance.
Note: There are a few un-used variables from ideas I was testing, but I couldn't make them work.
You can try:
if (source.indexOf(searchString) !== -1) {
// Match!
}
else
{
//No Match!
}
As the other answers so far point out, JavaScript strings have an indexOf function that does what you want. If you want to see how it's done "by hand", you can modify your function like this:
var sourceSearch = function(text) {
var i, j, ok; // always declare your local variables. globals are evil!
// for each start position
for(i = 0; i < source.length; i++) {
ok = true;
// check for a match
for (j = searchString.length - 1; ok && j >= 0; --j) {
ok = source[i + j] === searchString[j];
}
if (ok) {
// searchString found starting at index i in source
}
}
};
This function will find all positions in source at which searchString was found. (Of course, you could break out of the loop on the first success.) The logic is to use the outer loop to advance to each candidate start position in source and use the inner loop to test whether that position actually is the position of a match to searchString.
This is not the best algorithm for searching strings. The built-in algorithm is much faster (both because it is a better algorithm and because it is native code).
to follow your approach, you can just play with 2 indexes:
var sourceSearch = function(text) {
j = 0;
for(i = 0; i < source.length; i++) {
if(source[i] === text[j]) {
j++;
} else {
j = 0;
}
if (j == text.length) {
console.log(i - j); //this prints the starting index of the matching substring
}
}
};
These answers are all pretty good, but I'd probably opt for something like this:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = source.split(searchString);
var hitsCount = hits.length - 1;
This way you have all of the data you need to figure out where each hit occurred in he source, if that's important to you.

Categories