Blogger Information
Blog 33
fans 1
comment 0
visits 21832
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js 中使用for或者forEach可以遍历数组, 请具体举例演绎其与PHP中for, foreach遍历数组的区别?
冰雪琉璃
Original
505 people have browsed it

js遍历数组的方法

1.for
2.forEach

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>for forEach遍历数组</title>
  8. </head>
  9. <body>
  10. <script>
  11. let arr=[1,2,3,4];
  12. //for遍历数组
  13. for(let i=0;i<arr.length;i++){
  14. arr[i];
  15. }
  16. //forEach遍历数组
  17. arr.forEach(function(item){
  18. alert(item);
  19. })
  20. </script>
  21. </body>
  22. </html>
  1. <!-- php数组的遍历 -->
  2. $cars=['奥迪','宝马','奔驰'];
  3. <!-- php for遍历数组 -->
  4. for($i=0;$i<count($cars);$i++){
  5. echo $cars[$i].'<br/>';
  6. }
  7. <!-- php forEach遍历 -->
  8. forEach($cars as $car){
  9. echo $car.'<br/>';
  10. }
  11. <!-- 带有key值的 php forEach遍历 -->
  12. forEach($cars as $k=> $car){
  13. echo $k.'=>'.$car.'<br/>';
  14. }
  15. <!-- 放在li标签中 -->
  16. <?php forEach($cars as $k=>$car){
  17. echo '<li><a href="">'.$car.'</a></li>';
  18. }
  19. >

总结js与php遍历数组的区别:

1.js在遍历数组时候要声明变量而php可以用$直接使用。
2.js用length属性获取数组的长度,而php用count()函数获取。

Correcting teacher:灭绝师太灭绝师太

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post