774 snippets from 1587 members, and growing!
|
login
|
join
about
bytebin
members
tags
snippets
join
Snippets
Submit a Snippet
Search Snippets
New Snippets
Top Snippets
Top Tags
PHP
(138)
JavaScript
(125)
Java
(66)
VBSCRIPT
(58)
String
(44)
CSS
(31)
CSharp
(28)
File
(28)
HTML
(27)
mysql
(25)
C
(24)
VB.NET
(24)
python
(24)
CPlusPlus
(23)
groovy
(23)
New Snippets
Clean PHP Templat...
PHP/MySQL impleme...
Analyte - Easy to...
Easy SQLite inter...
Very lightweight ...
AutoComplete plug...
AutoComplete plug...
Connection Java -...
View PostgreSql
Store Procedure
Venture Capital Jobs
New Members
me
jamesmcm
Can
Kelmi
ysg
dannymo2
chorny
wallie
Hackdemian
impomatic
Top Members
dannyboy
sundaramkumar
mattrmiller
Pio
i_kenneth
ASmith
ctiggerf
sehrgut
bertheymans
SCoon
Home
/
Snippets
/
Emulating the PHP foreach(){...} in javascript
/
Comments
Emulating the PHP foreach(){...} in javascript
Snippet Menu
Revisions
Comments
Related Snippets
Add to Favorites
Email Snippet
Download Snippet
Print Snippet
Blog Snippet
snippet
|
revisions
|
comments
|
related
|
Add to Favorites
|
email
download
|
print
|
blog it
New Comment
PHP forEach
Thu. Mar. 8th, 2007 1:53 PM
Fordiman
That won't work for objects / associative arrays... but this will.
for
(
i
in
objArray
)
{
var
v=objArray
[
i
]
;
}
Reply
Extending the core...
Tue. Mar. 6th, 2007 7:03 PM
albud
JavaScript provides an array method called forEach that can be used much like the foreach in PHP, but I can't remember if it's available in all JavaScript environments.
I personally use the code below to do the same thing.
Array.
prototype
.
each
=
function
(
f
)
{
for
(
var
i=
0
;i<this.
length
;i++
)
f
(
this
[
i
]
,i
)
;
}
d =
[
"a"
,
"b"
,
"c"
]
d.
each
(
function
(
item
, index
)
{
alert
(
index +
": "
+
item
)
;
}
)
;
Reply
No there isn't
Wed. Nov. 28th, 2007 7:51 AM
HRCerqueira
What you have in javascript is this:
var
test =
{
x:
'a'
, y:
'b'
, z:
'c'
}
;
for
(
value
in
test
)
{
alert
(
value
)
;
alert
(
test
[
value
]
)
;
}
Reply
Nice!!
Thu. Mar. 8th, 2007 11:10 AM
shachi
Nice one!
Reply
New Comment
for (i in objArray) {
var v=objArray[i];
}
I personally use the code below to do the same thing.
Array.prototype.each = function (f) {
for (var i=0;i<this.length;i++)
f(this[i],i);
}
d = ["a", "b", "c"]
d.each(function (item, index) {
alert(index + ": " + item);
});
var test = {x: 'a', y: 'b', z: 'c'};
for (value in test) {
alert(value);
alert(test[value]);
}