How to make simple php's foreach equivalent in Javascript?
Possible Duplicate:
Loop through array in JavaScript
I want to make the equivalent of php's foreach in javascript. Because I don't really know the Javascript language, I'd like someone to rewrite this PHP code into the Javascript piece:
$my_array = array(2 => 'Mike', 4 => 'Peter', 7 => 'Sam', 10 => 'Michael');
foreach($my_array as $id => $name)
{
echo $id . ' = ' . $name;
}
Is that even possible to do in the Javascript language?
最接近的构造是
a = { 2: 'Mike', 4: 'Peter', 7: 'Sam', 10: 'Michael' };
for(var n in a) {
console.log(n+'='+a[n]);
}
In JQuery, The $.each
function is similar.
It allows you to iterate arrays using a callback function where you have access to each item:
var arr = [ "one", "two", "three", "four", "five" ];
$.each(arr, function(index, value) {
// work with value
});
Plain javascript?
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
See below url
foreach equivalent of php in jquery?
Or try it
If you want to iterate an object, I would recommend the JavaScript variant:
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
You can also iterate objects in jQuery like this: Note! Doing this is pretty pointless unless you think this syntax is much simpler to maintain. The below syntax has much more overhead than the above, standard JavaScript, for-loop.
$.each(obj, function (key, value) {
alert(key + ': ' + value);
});
To iterate arrays, this is how you do it in standard JavaScript (assuming arr is the array):
for (var i = 0, l = arr.length; i < l; i++) {
alert(i + ': ' + arr[i]);
}
To do it in jQuery, you can do it like this:
$.each(arr, function (index, value) {
alert(index + ': ' + value);
});
链接地址: http://www.djcxy.com/p/24526.html
上一篇: 通过嵌套的对象属性进行循环