JS loop producing no result [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Trying to create an array with a loop and then sum all the contents of the array and put the result as the contents of a DIV but when I run the fiddle I get no result and jshint says everything is well formed.
var begin = 500000;
var stop = 999999;
var arrInt = [];
// Create an array worth summing
var CreateArray = function (begin,stop) {
while(begin < stop +1){
arrInt.push(begin++);
}
};
// Sum all ints in an array
var IntSum = function (ManyInts) {
var i = arr.length; while (i--) {
return;
}
};
var example = document.getElementById("example").innerHTML;
example=IntSum(arrInt);
<div id="example"></div>
http://jsfiddle.net/7b8rqme5/

At no point do you call CreateArray. You call your other function, IntSum, which does precisely nothing. Also, you create a variable example and assign a dom element to it, then you immediately overwrite it with a (noop) function result. There are additional issues with your code as well.
My advice: slow down, determine what it is you need to accomplish, and take it step by step.

I think this is what you wanted. But not really sure what you are trying to do here.
var begin = 500000;
var stop = 999999;
var arrInt = [];
var CreateArray = function (begin,stop) {
while(begin < stop +1){
arrInt.push(begin++);
}
};
var IntSum = function (ManyInts) {
var sum = 0
var i = ManyInts.length; while (i--) {
sum += ManyInts[i];
}
return sum;
};
var example = document.getElementById("example").innerHTML;
CreateArray(begin, stop);
var saic=IntSum(arrInt);
document.getElementById("example").innerHTML = saic
http://jsfiddle.net/wpnkL6k2/

Related

JavaScript Infinity loop in foreach statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i wrote this code and he executed in an infinite loop
var listStock=[{"price":200,"libelle":"bus"},{"price":5,"libelle":"grand taxi"},{"price":6,"libelle":"tram"},{"price":12,"libelle":"tram"},{"price":95,"libelle":"librairie"},{"price":22,"libelle":"food"},{"price":6,"libelle":"tram"},{"price":6,"libelle":"tram"},{"price":15,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":10.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":13.5,"libelle":"librairie"},{"price":20,"libelle":"librairie"},{"price":20,"libelle":"arrondissement"},{"price":15,"libelle":"grand taxi"},{"price":9,"libelle":"librairie"},{"price":34,"libelle":"food"},{"price":10,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":3.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":7.5,"libelle":"grand taxi"},{"price":33,"libelle":"tran"},{"price":4,"libelle":"pisri"},{"price":15,"libelle":"grand taxi"},{"price":5,"libelle":"pisri"},{"price":20,"libelle":"tobis"},{"price":6,"libelle":"grand taxi"},{"price":45,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":4,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":120,"libelle":"tran"},{"price":3,"libelle":"librairie"},{"price":8,"libelle":"pisri"},{"price":60,"libelle":"covoiturage"},{"price":7,"libelle":"grand taxi"},{"price":7,"libelle":"tram"},{"price":2,"libelle":"pisri"},{"price":1,"libelle":"gift"},{"price":29,"libelle":"food"},{"price":23,"libelle":"covoiturage"}];
var listLib=[];
listStock.forEach(function(item, index) {
var lib=item.libelle;var pr=item.price;
if(listLib.length==0){
var objet={};objet.libelle=lib;objet.price=pr;
listLib.push(objet);
}else{
listLib.forEach(function(item1,index1){
if(item1.libelle==lib){
item1.price=item1.price+pr;
}else{
var objet={};objet.libelle=lib;objet.price=pr;
listLib.push(objet);
}
});
}
});
i want to sum prices by label
You are using listLib.push inside a loop on listLib, and you are doing this for every iteration where the object does not match. And so you repeatedly add a similar object to listLib.
You should just find the matching entry, and potentially add a new object after that search, not during the search. So if we stick to your code, then the else part of your code should be modified to this:
var found = false;
for (let item1 of listLib) {
if(item1.libelle==lib){
item1.price=item1.price+pr;
found = true;
break; // No need to look further
}
}
// And then AFTER the loop, check if we need to add the object:
if (!found) {
var objet={};objet.libelle=lib;objet.price=pr;
listLib.push(objet);
}
Even better is to key your input data first, using a Map. Because then the look-up is easy and has better performance:
var listStock=[{"price":200,"libelle":"bus"},{"price":5,"libelle":"grand taxi"},{"price":6,"libelle":"tram"},{"price":12,"libelle":"tram"},{"price":95,"libelle":"librairie"},{"price":22,"libelle":"food"},{"price":6,"libelle":"tram"},{"price":6,"libelle":"tram"},{"price":15,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":10.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":13.5,"libelle":"librairie"},{"price":20,"libelle":"librairie"},{"price":20,"libelle":"arrondissement"},{"price":15,"libelle":"grand taxi"},{"price":9,"libelle":"librairie"},{"price":34,"libelle":"food"},{"price":10,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":3.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":7.5,"libelle":"grand taxi"},{"price":33,"libelle":"tran"},{"price":4,"libelle":"pisri"},{"price":15,"libelle":"grand taxi"},{"price":5,"libelle":"pisri"},{"price":20,"libelle":"tobis"},{"price":6,"libelle":"grand taxi"},{"price":45,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":4,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":120,"libelle":"tran"},{"price":3,"libelle":"librairie"},{"price":8,"libelle":"pisri"},{"price":60,"libelle":"covoiturage"},{"price":7,"libelle":"grand taxi"},{"price":7,"libelle":"tram"},{"price":2,"libelle":"pisri"},{"price":1,"libelle":"gift"},{"price":29,"libelle":"food"},{"price":23,"libelle":"covoiturage"}];
let map = new Map(listStock.map(({libelle}) => [libelle, {libelle, price: 0}]));
for (let {price, libelle} of listStock) map.get(libelle).price += price;
let result = Array.from(map.values());
console.log(result);
var listStock=JSON.parse(`[{"price":200,"libelle":"bus"},{"price":5,"libelle":"grand taxi"},{"price":6,"libelle":"tram"},{"price":12,"libelle":"tram"},{"price":95,"libelle":"librairie"},{"price":22,"libelle":"food"},{"price":6,"libelle":"tram"},{"price":6,"libelle":"tram"},{"price":15,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":10.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":13.5,"libelle":"librairie"},{"price":20,"libelle":"librairie"},{"price":20,"libelle":"arrondissement"},{"price":15,"libelle":"grand taxi"},{"price":9,"libelle":"librairie"},{"price":34,"libelle":"food"},{"price":10,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":3.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":7.5,"libelle":"grand taxi"},{"price":33,"libelle":"tran"},{"price":4,"libelle":"pisri"},{"price":15,"libelle":"grand taxi"},{"price":5,"libelle":"pisri"},{"price":20,"libelle":"tobis"},{"price":6,"libelle":"grand taxi"},{"price":45,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":4,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":120,"libelle":"tran"},{"price":3,"libelle":"librairie"},{"price":8,"libelle":"pisri"},{"price":60,"libelle":"covoiturage"},{"price":7,"libelle":"grand taxi"},{"price":7,"libelle":"tram"},{"price":2,"libelle":"pisri"},{"price":1,"libelle":"gift"},{"price":29,"libelle":"food"},{"price":23,"libelle":"covoiturage"}]`);
//console.log(listStock)
const finalData=listStock.reduce((acc,curr)=>{
const label=curr.libelle;
acc[label]=acc[label]? acc[label]+ curr.price : curr.price || 0;
return acc;
},{})
console.log(finalData)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Add onclick event to array items [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to iterate over an array and apply an onclick event to each item. I'm hoping to be able to click each of my divs and have them console log their value. Right now I'm stuck on how to apply the onclick to each div. I'm new to JS, so I'm not completely of why I shouldn't make a function inside of a loop like JSBin is complaining about. I've messed around with a lot of different ways to do this, but am truly stuck...
JSBin
function numberTrack() {
var gridItems = document.getElementsByClassName("grid");
for (var i = 0; i < gridItems[0].length; i ++) {
gridItems.onclick = function(){
alert("hello");
};
}
}
numberTrack();
var c = document.getElementsByClassName("divs"); <--- array of divs
for (var i = 0; i < c.length; i++) {
c[i].onclick = function() {
console.log(this.value);
}
}
JSBin is complaining because it wants you to declare the function outside the for loop and then assign it inside the for loop. This is more efficient then what you are currently doing, which is assigning a new anonymous function to each item in the array. All those identical functions will have to be created and stored separately in memory.
You can do something like this instead:
function alertHello() {
alert("hello");
}
for (var i = 0; i < gridItems.length; i++) {
gridItems[i].onclick = alertHello;
}
You need to loop through all the items in the gridItems collection, And inside the loop, get each item using the iterator i value.
function handleClick()
{
alert("hello");
}
function numberTrack() {
var gridItems = document.getElementsByClassName("grid");
for (var i = 0; i < gridItems.length; i ++) {
gridItems[i].onclick = handleClick;
}
}
numberTrack();
If you are allowed to use jQuery, you can bind the event to items like this.
$(function(){
$(document).on("click",".grid",function(e){
var item =$(this);
alert(item.html())
})
})
Here is a working jsBin sample

JavaScript array push not working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to push a value into an array and it is giving me this error in the developer tools.
Uncaught TypeError: Cannot read property 'push' of null
Here is the code that it seems to be sticking on, word and local word were defined earlier like this.
var word = [];
var localWord = [];
function setLocalArray() {
// first get words from text field and update word array.
word = document.getElementById("words").value.split(',');
// store word array in localStorage
for(var i=0; word.length > i; i++) {
var key2 = "part"+i;
localStorage.setItem(key2,word[i]);
localWord.push(key2);
}
localStorage.setItem("localWord",JSON.stringify(localWord));
text2Array();
reveal();
}
localWord.push(key2); Seems to be what it is getting stuck on. I have looked at everything I can find on the push method and I can't seem to find why it is giving me this error. Help?
Here is the full code at jsfiddle http://jsfiddle.net/runningman24/jnLtpb6y/
Try this...
var localWord = new Array(); //create new array
var word = new Array();
function setLocalArray() {
word = document.getElementById("words").value.split(',');
// store word array in localStorage
for(var i=0; word.length > i; i++) {
var key2 = "part"+i;
localStorage.setItem(key2,word[i]);
localWord.push(key2);
}
}
I found the problem, if you look in the jsfiddle I posted I am trying to pull localWord from localStorage even though it doesn't exist and so it sets it to null. Thank you to all for the ideas and contributions.
You could try isolating the scope of your variable using the module pattern:
var arrayManager = (function () {
var word = [];
var localWord = [];
function setLocalArray() {
// first get words from text field and update word array.
word = document.getElementById("words").value.split(',');
// store word array in localStorage
for(var i=0; word.length > i; i++) {
var key2 = "part"+i;
localStorage.setItem(key2,word[i]);
localWord.push(key2);
}
localStorage.setItem("localWord",JSON.stringify(localWord));
text2Array();
reveal();
}
return {
setLocalArray:setLocalArray
} ;
}());
and the from the outside you have to simply call arrayManager.setLocalArray()

How do I use repeated value in innerhtml? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I used this code but it's not repeat
it increase the value but don't get to the initial value 0
please help
i=0;
function loading()
{
text=["Loading.","Loading..","Loading...","Loading...."];
window.setInterval(wr(),500)
}
function wr()
{
if(i<4)
{
wr='document.getElementById("text").innerHTML=text[i]';
alert(i);
}
else
i=0;
return wr;
}
Your code is way to complicated. Define a simple function which you pass to setInterval and make sure you increase the counter variable:
var i = 0; // initialize counter
var textElement = document.getElementById("text");
setInterval(function() {
i = i % 4; // make sure `i` is at max 3 and reset to 0
var text = 'Loading';
for (var j = i; j--; ) {
text += '.'; // add the correct number of periods
}
textElement.innerHTML = text; // set text
i++; // increase counter
}, 500);
DEMO
Here's a slight modification of a similar answer I gave a while back.
var i = 0;
setInterval(function() {
i = ++i % 4;
document.getElementById('text').innerHTML = "Loading"+Array(i+1).join(".");
}, 500);

Can i make my code shorter? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I have many functions for calculating some stats , and i need to recheck the value's every time but that is extra code and make's it harder to read , can i store the variable assignment in another function:
function MC () {
var check=document.getElementById('check').checked;
var ea=Number(document.form.ea.value),
ed=Number(document.form.ed.value),
pa=Number(document.form.pa.value),
pd=Number(document.form.pd.value);
var hpSum = 0,spSum=0,eaSum=0,edSum=0,pdSum=0,paSum=0;
if(check){
eaSum = ea + 11;
edSum = ed + 17;
pdSum = pd + 17;
paSum = pa + 11;
} else {
eaSum = ea - 11;
edSum = ed - 17;
pdSum = pd - 17;
paSum = pa - 11;
}
document.form.ea.value=eaSum;
document.form.ed.value=edSum;
document.form.pa.value=paSum;
document.form.pd.value=pdSum;
};
NOTE:I am speaking for the variables:ea,ed,pa,pd and sum variables.
You could try building an object of parameters:
function MC() {
var check = document.getElementById('check').checked,
keys = {
"ea":11,
"ed":17,
"pd":17,
"pa":11
}, i;
for( i in keys) { if( keys.hasOwnProperty(i)) {
document.form[i].value = +document.form[i].value + (check ? keys[i] : -keys[i]);
}}
}
Note that +somevar is a cheap shortcut for parseFloat(somevar). Number(somevar) is NOT the same as it creates a wrapper object that may interfere with comparisons if you add any in later.
I'd go with your own code, condensed a bit. Assuming form is the name of a form, it would take more code to keep track which inputs have changed than to read them.
function MC () {
var f= document.form,
v= document.getElementById('check').checked? [11, 17]:[-11, -17];
f.ea.value= Number(f.ea.value)+v[0];
f.ed.value= Number(f.ed.value)+v[1];
f.pa.value= Number(f.pa.value)+v[0];
f.pd.value= Number(f.pd.value)+v[1];
}

Categories