Blogger Information
Blog 34
fans 0
comment 0
visits 18397
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0425PHP编程作业
千山暮雪
Original
478 people have browsed it

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

  • for

    语法:
    for (初始化表达式1; 判断表达式2; 自增表达式3) {
    // 循环体4
    }

  1. let items = ['一', '二', '三', '四', '五'];
  2. for (let i = 0; i < items.length; i++) {
  3. console.log(items[i]); // 一 二 三 四 五
  4. }
  • for in / for of

    for in是ES5标准,遍历key.
    for of是ES6标准,遍历value.

  1. let items = ['一', '二', '三', '四', '五'];
  2. for (let item in items) {
  3. console.log(item); // 0 1 2 3 4
  4. }
  5. for (let item of items) {
  6. console.log(item); // 一 二 三 四 五
  7. }
  • foreach()

    foreach是数组对象的一个方法.方法为每个数组元素调用一次函数(回调函数)
    语法:Array<number>.forEach( callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any): void

  1. let items = ['一', '二', '三', '四', '五'];
  2. items.forEach((item, index) => console.log(index,item)); // 0,一 1,二 2,三 3,四 4,五

PHP中for, foreach遍历数组

  • for

    语法:语法
    for(初始值;条件;增量){
    //循环体
    }

  1. $items = [1, 2, 3, 4, 5];
  2. for ($i=0; $i < count($items); $i++) {
  3. echo $items[$i]; // 1 2 3 4 5
  4. }
  • foreach

    语法:
    //语法一
    foreach(数组 as 值){
    }
    //语法二
    foreach(数组 as 键=>值){
    }

  1. $items = [1, 2, 3, 4, 5];
  2. foreach ($items as $k => $v) {
  3. echo $k,$v;
  4. }
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