For loop repeating first iteration twice - javascript

I am having an issue with a javascript for loop. I am adding up the elements of an array, but for some reason my loop adds in the first entry twice! There was a similar topic on here before (http://stackoverflow.com/questions/3121670/for-loop-repeats-first-loop-twice) but the author didn't go into his resolution in detail, just that it was "somethin stupid" he did. Can anyone tell me what I'm doing stupid??
for(j=0;j<ARRAY.length;j++)
{TOTAL += ARRAY[j];}
The output is used in a HTML table and it is displaying correctly, it's just the doubled first entry that's the issue!
Any help would be greatly appreciated.

var TOTAL = 0;
for ( var j = 0, len = ARRAY.length; j < len; j++ ) {
TOTAL += ARRAY[j];
}
MDN suggest to use a variable to hold the array length. In addition check your scripts with JSLint.

make sure you declare with var...
Nice little bit of prompting debugging in there too.
for(var j=0; j < ARRAY.length; j++) {
{
TOTAL += ARRAY[j];
//alert("The count of J is now " + j);
}

Thanks for all of your help. Since my original approach hit a dead end I looked into using a function to do the trick. The following works:
Array.prototype.sum = function() {
for (var j = 0, L = this.length, sum = 0; j < L; sum += this[j++]);
return sum;
}
I then call ARRAY.sum() when creating my html table.
I found the above solution on http://www.codingforums.com/showthread.php?t=218803

Related

How to Diplay block of numbers of given input numbers

I want to display a block of numbers of the input with input times
basic web pages
var j= "";
var n=prompt("Enter the size of the box");
for(var i=1; i<=n; i++)
{
document.write(i +"<br>");
}
if the given input is 5 the output should be as follows:
o/p
12345
12345
12345
12345
12345
prompt() method only returns a string. So, first you need to convert the string to a number using parseInt()
var num = prompt('Enter the size of the box: ');
num = parseInt(num);
for(let i = 1; i <= num; i++) {
for(let j = 1; j <= num; j++) {
document.write(j+' ');
}
document.write('</br>');
}
var j= "";
var n=prompt("Enter the size of the box");
var x = [ ...Array(n*1+1).keys() ].join('').substring(1);
for(var i=1; i<=n; i++)
{
document.write(x +"<br>");
}
This will solve your problem .
var j= "";
var n=prompt("Enter the size of the box");
for(var i=1; i<=n; i++)
{
for(var j = 1; j<=n ; j++ ){
document.write(j);
}
document.write("<br>");
}
I guess you are new to programming and this example wants to teach you nested loops.
You'll have to split up your task to the smallest possible steps and think about what is happening in your loops. The best way is to work "inside-out".
So first you think about what is a single step you want to do: printing a number.
After that you'll think about how often you want to print it in a row.
After that you'll think about how you want to separate the rows.
In the final step you'll think about how many rows you want to print.
The code above will work for you now, but if you don't think about it, you'll fail at the next similar problem.
Give a man a fish and you'll feed him for a day. Teach a man to fish, and you'll feed him for a lifetime! ;-)

Any alternative way of using this .charAt()?

I have a problem, when I used input[index] in the statement the reverse word didn't match the value of inputString. But this works in C#. When I try it in JavaScript is not working. I want to learn what are the other alternative way of .char() method. Can anybody solve my problem?
strReverse = "";
input = document.getElementById("inputValue").value;
i = input.length;
for(var j = i; j >= 0; j--) {
strReverse = strReverse + input.charAt(j); // i used input[index]
}
If you wish to use input[index] instead of input.charAt() then you need to address the issue that you are setting i = input.length;
So when you enter your loop for the first iteration, j will be equal to i. Meaning that you are trying to access the character at the index equal to the length of the string (when you do input[j]). However, as arrays and string indexing starts at zero in javascript (and in most languages), there is no index at i (the length of the string), but, there is an index at i-1, which will give the last character in the string. Thus, if you want to reverse your array using input[j] you need to start j in your for loop as j = i - 1.
Take a look at the snippet for a working example:
strReverse = "";
input = "level";
i = input.length;
for(var j = i-1; j >= 0; j--) {
strReverse = strReverse + input[j]; // i used input[index]
}
if(strReverse === input) {
alert(input +" is a palindrome!")
} else {
alert(input +" is not a palindrome!");
}

Updating Matrix Array

I need to make a grid that looks like this in javascript using one function:
x---------
xx--------
xxx-------
xxxx------
xxxxx-----
xxxxxx----
xxxxxxx---
xxxxxxxx--
xxxxxxxxx-
xxxxxxxxxx
and this:
x---------
xx--------
xxx-------
xxxx------
xxxxx-----
xxxxx-----
xxxx------
xxx-------
xx--------
x---------
//Build Matrix
function initMatrix(max) {
var myMatrix = [];
var i;
for(i = 0; i < row; i++){
myMatrix.push([]);
var j;
for(j = 0; j < col; j++) {
if(j < max) {
myMatrix[myMatrix.length - 1].push('*');
} else {
myMatrix[myMatrix.length - 1].push('-');
}
}
}
return myMatrix;
}
More of this code can be viewed here
https://jsfiddle.net/0yc7acev/
Thanks in advanced for the help!
Hi I've made you this document that explains how to do this and has both solutions: https://tonicdev.com/tonic/stars-example . Let me know if you have any questions!
Edit: I realized after the fact that you wanted them in a matrix, not a string, so I've made a slight modification to put them in a matrix for you: https://tonicdev.com/tonic/stars-matrix (the old one still shows how to put them all in string).
The solution at the end is just:
function drawStars(starCounts)
{
return starCounts.map(function (starCount)
{
return (new Array(starCount + 1).join("*") +
new Array(lineLength - starCount + 1).join("-")).split("")
});
}
where starCounts is an array.

Sorting strings from prompt is not working but it works when hard coded

My code is not working when I give the value via prompt but is working with hard coded input.
Could someone please help me understand why that is?
var str=prompt("Enter String :: ");
alert(selectionSort(str));
function selectionSort(items){
var len = items.length,
min;
for (i=0; i < len; i++){
min = i;
//check the rest of the array to see if anything is smaller
for (j=i+1; j < len; j++){
if (items[j] < items[min]){
min = j;
}
}
if (i != min){
swap(items, i, min);
}
}
return items;
}
This is my swapping function:
function swap(items, firstIndex, secondIndex){
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
If you just want to sort the characters you can use:
var str = "farhan";
var sorted = str.split("").sort().join("");
console.log(sorted); // "aafhnr"
.split("") turns the string into an array. .sort sorts the array (default is ascending order) and .join("") turns the array back into a string.
For educational purposes it might be useful to write your own sort routine, but beyond that, use the built in functions as much as you can.

Loop that finds a word in a string

So, i'm working on a 'for' loop that will identify my name, Andrew, and push it into an array, but there's something wrong with it
/*jshint multistr:true */
var text = ("Andrew is really awesome and Andrew should be working on the project, but there is honestly nothing for Andrew to do.");
var myName = ("Andrew");
var hits = [];
for (var i = 0; i < text.length; i ++) {
if (text[i] === "A") {
for (var j = i; i + nyName.length; i ++) {
hits.push(text[j]);
}
}
}
Also, the second loop is supposed to stop when it reaches the end of myName.
You're using JSHINT, so just read the error messages and it'll tell you exactly what's wrong.
Errors:
Line 7: for (var j = i; i + nyName.length; i ++) {
'nyName' is not defined.
Line 3: var myName = ("Andrew");
'myName' is defined but never used.
JSHINT isn't much good if you don't pay attention to what it's telling you.
Also, your inner loop looks odd.
for (var j = i; i + nyName.length; i ++) {
Seems like it'll cause an infinite loop. You're perhaps wanting j with a different condition.
You misspelled myName in your for loop syntax and typed nyName instead, so chances are the script dies as soon as it hits that line.
A typo in the for loop that wants to refer to myName would appear to be a big problem:
for (var j = i; i + nyName.length; i ++)
^
The misspelled myName isn't the only part that fails. You for loop will never end the loop because i + myName.length will always evaluate to true. You also need to increase the value of j or it will always get the character at index i.
Here's the corrected loop.
for (var i = 0; i < text.length; i ++) {
if (text[i] === "A") {
for (var j = 0; j < myName.length; i++, j++) {
hits.push(text[i]);
}
}
}

Categories

Resources