All Questions

2049
votes
32answers
249375 views

JavaScript closure inside loops – simple practical example

var funcs = []; for (var i = 0; i < 3; i++) { // let's create 3 functions funcs[i] = function() { // and store them in funcs console.log("My value: " + i); // each should...
314
votes
10answers
194072 views

Asking the user for input until they give a valid response

I am writing a program that must accept input from the user. #note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input` age = int(input("Please enter your age: ")) if age >= 1...
3402
votes
22answers
3056784 views

For-each over an array in JavaScript?

How can I loop through all the entries in an array using JavaScript? I thought it was something like this: forEach(instance in theArray) Where theArray is my array, but this seems to be incorrect....
1825
votes
26answers
1134486 views

How do I loop through or enumerate a JavaScript object?

I have a JavaScript object like the following: var p = { "p1": "value1", "p2": "value2", "p3": "value3" }; Now I want to loop through all p elements (p1,p2,p3...) and get their keys and...
315
votes
32answers
72358 views

What is the most "pythonic" way to iterate over a list in chunks?

I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list...
1312
votes
22answers
774664 views

Iterate through object properties

var obj = { name: "Simon", age: "20", clothing: { style: "simple", hipster: false } } for(var propt in obj){ alert(propt + ': ' + obj[propt]); } How does the var...
221
votes
19answers
263852 views

How do I add a delay in a JavaScript loop?

I would like to add a delay/sleep inside a while loop: I tried it like this: alert('hi'); for(var start = 1; start < 10; start++) { setTimeout(function () { alert('hello'); }, 3000); } ...
2174
votes
13answers
1075121 views

Accessing the index in Python 'for' loops

How do I access the index itself for a list like the following? ints = [8, 23, 45, 12, 78] When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case?
1448
votes
7answers
301383 views

How does PHP 'foreach' actually work?

Let me prefix this by saying that I know what foreach is, does and how to use it. This question concerns how it works under the bonnet, and I don't want any answers along the lines of "this is how you...
2579
votes
7answers
2821889 views

Iterate through a HashMap

Possible Duplicate: How do I iterate over each Entry in a Collection Map? What's the best way to iterate over the items in a HashMap?

Previous Next