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.
Related
I'm making a small script that will iterate the numbers and skip the number 5. I want to achieve this with continue; statement/label.
Here is my code:
<p id="test"></p>
<script>
var i, text;
text = "";
i = 0;
for (;i<8;) {
if (i === 5) {continue;}
text += "The number is " + i + "<br>";
i++;
}
document.getElementById('test').innerHTML = text;
</script>
I'm failing to see any typo error, but coding for more than 12 hours now, maybe I'm overseeing something obvious. If so, I apologize.
This works when I want to stop at number 5 using break; statement.
<p id="test"></p>
<script>
var i, text;
i = 0;
text = "";
for (;i<8;) {
if (i === 5) {break;}
text += "The number is " + i "<br>";
i++;
}
document.getElementById('test').innerHTML = text;
</script>
if (i === 5) {continue;}
will never allow the control to go ahead and increment the i. Thus, it'll always go back when i becomes five.
Solution:
if (i === 5) {
i++; // Increament `i` first
continue;
}
OR, using for third argument.
for (; i<8; i++) {
^^^ // Increment `i` for each iteration
One more simple thing can be done using if condition.
for (; i < 8; i++) {
// If i is not 5, then only append to the string.
if (i !== 5) {
text += "The number is " + i + "<br>";
}
}
This is causing an infinite loop as your value is never being incremented. continue will move onto the next iteration, however since you haven't defined a statement to increment your value, this never occurs.
Consider refactoring your loop as follows as opposed to performing your incrementation within the body of the loop:
<script>
var text = "";
// This is the most common approach to defining a for-loop as it handles defining
// your iterator, defining a stop condition and handles how to increment your value
// after each iteration
for (var i = 0; i < 8; i++) {
if (i === 5) {break;}
text += "The number is " + i "<br>";
}
document.getElementById('test').innerHTML = text;
</script>
if (i === 5) {continue;}
When i is 5 it never gets a chance again to reach i++. So, i will ever be 5 and you will never exit the loop.
For my Javascript course I got this code:
for (var i in window.navigator)
{
document.getElementById('divResult').innerHTML +=
i + ': ' + window.navigator[i] + '<br />';
}
</script>
The teacher (online) wants me to limit the results into maximal 10.
For me this is a big puzzle. From other questions about the for..in I think to know it is a discussable statement. But how to approach this for..in? As an array with i.length?
Just set a counter. In each iteration you increase the counter and when the counter reaches 10 you simply break out of your loop
Code:
// Since we're going to access this div multiple times it's best to
// store it outside of the for loop.
var output = document.getElementById('divResult');
var counter = 0;
for (var elem in window.navigator) {
var value = window.navigator[elem];
output.innerHTML += counter + ': ' + elem + '=' + value + '<br />';
++counter;
if (counter == 10) {
break;
}
}
Since you're new to JavaScript I would like to explain a little bit about for-in
If you want to get a specific value from an array you access it's element by index. So for example:
var myArray = [7, 5, 6, 6];
for (var i = 0; i < myArray.length; ++i) {
var value = myArray[i];
}
But now you want to loop through window.navigator and this element is not an array but a object. And since a object is key-value it does not have a index. So how do you loop through it?
Let's imagine window.navigator looks like this:
var navigator = {
myBrowser: 'Google Chrome',
myOtherProperty: 'otherValue',
AnotherProperty: 'anotherValue'
};
If we want to get the first element from our object we use
navigator.myBrowser
or
navigator['myBrowser'];
Now we want to loop through all the elements in our object. Since the normal for loop uses a index and objects don't have indexes we use the for in loop. This loop iterates through all the properties of our object and gives us the key.
for (var key in navigator) {
// Here we access a property in our object by the key given by our for loop.
var value = navigator[key];
}
So the first iteration our key is myBrowser and the value is Google Chrome
The next iteration the key is myOtherProperty and the value otherValue.
It is usually a good idea to use hasOwnProperty if you're looping through an object:
for (var key in navigator) {
if (navigator.hasOwnProperty(key) {
var value = navigator[key];
}
}
Hope this helps
The teacher came back with an answer for my for..in array problem:
<script>
var navigatorArray = [];
for (var i in window.navigator) {
navigatorArray.push(window.navigator[i]);
}
navigatorArray.sort();
console.log(navigatorArray);
var htmlString = '';
for (var j = 0; j < navigatorArray.length; j++) {
htmlString += navigatorArray[j] + '<br />';
}
with the .push habbit it should be possible to collect them in an array and index them.
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.
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]);
}
}
}
I'd like my output has 6 random numbers but my code only displays 4 numbers, and the numbers are the same.
var x = Math.floor(Math.random()*41);
for(var i=0; i<7; i++){
document.write(x + "</br>");
i++;
}
Could someone please help?
You need to move .random() inside your loop. Also, remove i++ from your loop, because that is already done by for().
Demo:
Script:
for( var i=0; i<6; i++ ){
var x = Math.floor(Math.random()*41);
document.write(x + "</br>");
}
You don't need the i++ inside the form, it's 6 not 7 and you need to calculate the random numbers inside the for loop.
for(var i=0; i<6; i++){
var x = Math.floor(Math.random()*41);
document.write(x + "</br>");
}
Why are you incrementing i twice? Also, if all the numbers are going to be random, you need to execute the Math function inside of the loop.
for(var i = 0; i < 6; i++) {
document.write(Math.floor(Math.random()*41) + "<br>");
}
You don't need to increment your counter twice. Also, the random() needs to be inside your loop.
var x = Math.floor(Math.random()*41);
for(var i=0; i<6; i++){
document.write(x + "</br>");
x = Math.floor(Math.random()*41);
}
you are assigning the var x with a random number before starting the loop, it remains same throughout the execution
try placing it inside the loop,also about incrementing the i, you are doing it in the for loop already so you do not need to do it inside the loop
var x = Math.floor(Math.random()*41);//place it inside the loop
for(var i=0; i<7; i++){
document.write(x + "</br>");
i++;//remove this
}