Loop that finds a word in a string - javascript

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

Related

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!");
}

Never ending for within for loop

I’m trying to convert text to binary but when my loop runs, it never ends. I cannot figure out why that is so.
Is there a better way to do this?
handleBinaryChange: function(e){
var friendsCopy = this.state.friendsArray;
for (var i = 0; i < friendsCopy.length; i++) {
for (var j = 0; j < friendsCopy[i].friendsName.length; j++) {
console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}//End of 'j' for
}//End of 'i' for
this.setState({
friendsArray: friendsCopy //make friendsCopy contain the new value for friendsName
});
}
}
By using += in friendsCopy[i].friendsName += you are modifying friendsCopy[i].friendsName. On each iteration it gets longer, so it never stops.
If you only want to output it to the console change it to
friendsCopy[i].friendsName + friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
You are increasing friendsName value with +=
in each loop iteration
simple solution: use an auxiliary test parameter that stores the starting value:
this way, test value is fixed throughout the entire loop
e.g.:
for(var i=0; i<friendsCopy.length; i++){
var test = friendsCopy[i].friendsName.length; // added this param
for(var j=0; j<test; j++){ // used it here
console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}//End of 'j' for
}//End of 'i' for
You are using the length of friendsName in your break condition, but you keep increasing the length of the string inside the loop:
for(var j=0; j<friendsCopy[i].friendsName.length; j++){
console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}
Note that friendsCopy[i].friendsName.length will be executed for each iteration of the loop, not only once at the beginning.

Loop in javascript to append a series of divs

This is my code, but it does not work.
for (i = 0; i < 5; i++) {
$(function(){
$('.tt'+ [i]).appendTo('.td'+ [i]);
});
}
I want the result:
$('.tt1').appendTo('.td1')
$('.tt2').appendTo('.td2')
$('.tt3').appendTo('.td3')
$('.tt4').appendTo('.td4')
$('.tt5').appendTo('.td5')
Please correct me, thanks you in advance!
You have some syntax errors, try this:
for (var i = 0; i <= 5; i++) {
$('.tt'+ i).appendTo('.td'+ i);
}
As already mentioned: remove the array initialization.
If you want to iterate from 1 to 5 then do so (not var = 0, but var i = 1):
for (var i = 1; i < 6; i++) {
$('.tt'+ i).appendTo('.td'+ i);
}
Also I don't see any sense in wrapping it the appendTo call.
The 1st Thing
You will never jump into the i=5 iteration
$('.tt5').appendTo('.td5')
because your for loop
for (i = 0; i < 5; i++)
ends at i = 5
Change it to
for (i = 1; i <= 5; i++)
It starts at i=1 because your example didn't show a ".tt0"
The 2nd thing
Remote the brackets!
Change
$('.tt'+ [i]).appendTo('.td'+ [i]);
to
$('.tt'+ i).appendTo('.td'+ i);
Otherwise you will create an Array and the JS interpreter performs an unnecessary Array.toString() operation.
The 3rd thing
I think you can remove the surrounding function inside the for loop
$(function(){
...
}
Just use:
for (var i = 1; i <= 5; i++) {
$('.tt'+ i).appendTo('.td'+ i);
}
See Fiddle
http://jsfiddle.net/Spaghettirocker/knkpaczg/1/

For loop in Javascript runs only once

Here is my code. I do not quite understand why the for loop runs only once, both inner and outer. nodeList.length and innerNodeList.length show appropriate values when I generate alert messages. I see that both i and j do not increment beyond 0. Kindly point out anything wrong with the code.
function getCategoryElements() {
var newCategoryDiv = document.getElementById("category");
var nodeList = newCategoryDiv.childNodes;
for (var i = 0; i < nodeList.length; ++i) {
var innerNodeList = nodeList[i].childNodes;
alert("innerNodeList Length" + innerNodeList.length.toString());
for (var j = 0; j < innerNodeList.length; ++j) {
if (innerNodeList[j].nodeName == "SELECT") {
alert("inside select Node value " + innerNodeList[j].nodeValue.toString());
document.getElementById("newCategories").value =
document.getElementById("newCategories").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
} else if (innerNodeList[j].nodeName == "TEXTAREA") {
document.getElementById("newCategoriesData").value =
document.getElementById("newCategoriesData").value + '<%=delimiter%>' + innerNodeList[j].nodeValue;
}
}
}
}
var newCategoryDiv, nodeList, innerNodeList, innerNode, i, j;
newCategoryDiv = document.getElementById("category");
nodeList = newCategoryDiv.childNodes;
for (i = 0; i < nodeList.length; ++i) {
innerNodeList = nodeList[i].childNodes;
alert("innerNodeList Length" + innerNodeList.length.toString());
for (j = 0; j < innerNodeList.length; ++j) {
innerNode = innerNodeList[j];
if (innerNode.nodeName === "SELECT") {
alert("inside select Node value " + innerNode.nodeValue.toString());
document.getElementById("newCategories").value += '<%=delimiter%>' + innerNode.nodeValue;
} else if (innerNode.nodeName === "TEXTAREA") {
document.getElementById("newCategoriesData").value += '<%=delimiter%>' + innerNode.nodeValue;
}
// Will this work?
alert('Does this alert appear');
}
}
I took the liberty to refactor your code and clean it up a little bit. In case you're not aware, all variables have function scope in Javascript, so no matter where you declare them within a single function, Javascript treats them as if the variable declaration is the first statement.
It appears that your code is syntactically correct, and so I think that the most logical place to look for a problem is that there could be an error occurring after the last alert function call.
In order to check this, try adding another alert function call to the end of the inner loop. If it doesn't run, you'll know this is the case.

For loop repeating first iteration twice

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

Categories

Resources