Blogger Information
Blog 52
fans 1
comment 1
visits 38277
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js 中使用for或者forEach遍历数组
小丑0o鱼
Original
1222 people have browsed it

js 中使用for或者forEach遍历数组

  1. for
  2. 语法:
  3. for (初始化表达式1; 判断表达式2; 自增表达式3) {
  4. // 循环体4
  5. }
  6. let items = ['一', '二', '三', '四', '五'];
  7. for (let i = 0; i < items.length; i++) {
  8. console.log(items[i]); // 一 二 三 四 五
  9. }
  10. for in / for of
  11. for inES5标准,遍历key.
  12. for ofES6标准,遍历value.
  13. let items = ['一', '二', '三', '四', '五'];
  14. for (let item in items) {
  15. console.log(item); // 0 1 2 3 4
  16. }
  17. for (let item of items) {
  18. console.log(item); // 一 二 三 四 五
  19. }
  20. foreach()
  21. foreach是数组对象的一个方法.方法为每个数组元素调用一次函数(回调函数)
  22. 语法:Array<number>.forEach( callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any): void
  23. let items = ['一', '二', '三', '四', '五'];
  24. items.forEach((item, index) => console.log(index,item)); // 0,一 1,二 2,三 3,四 4,五
  25. PHPfor, foreach遍历数组
  26. for
  27. 语法:语法
  28. for(初始值;条件;增量){
  29. //循环体
  30. }
  31. $items = [1, 2, 3, 4, 5];
  32. for ($i=0; $i < count($items); $i++) {
  33. echo $items[$i]; // 1 2 3 4 5
  34. }
  35. foreach
  36. 语法:
  37. //语法一
  38. foreach(数组 as 值){
  39. }
  40. //语法二
  41. foreach(数组 as 键=>值){
  42. }
  43. $items = [1, 2, 3, 4, 5];
  44. foreach ($items as $k => $v) {
  45. echo $k,$v;
  46. }
Correction status:Uncorrected

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!