js--循环处理

78 阅读3分钟

js--循环处理

for循环

var list1 = [
             {code:'1',name:'一一',status:1,amount:100,mark_no:1},
             {code:'2',name:'二二',status:1,amount:200,mark_no:1},
             {code:'3',name:'三三',status:2,amount:300,mark_no:2},
             {code:'4',name:'四四',status:2,amount:300,mark_no:2},
             {code:'5',name:'五五',status:2,amount:1000,mark_no:3},
             {code:'6',name:'六六',status:3,amount:1000,mark_no:3},];
for (let i = 0;i<list1.length;i++) {
    if (list[i].status == 1) {
        continue;    // 退出本次循环
    }
    console.log(list[i].code);    // 3 4 5 6
}

for (let i = 0;i<list1.length;i++) {
    if (list[i].status == 2) {
        break;    // 立即退出for循环,执行循环之后的代码
    }
    console.log(list[i].code);    // 1 2
}

for (let i = 0;i<list1.length;i++) {
    if (list[i].status == 2) {
        return;    // 函数终止执行,立即退出for循环,且有一个返回值,未指定时是undefined
    }
    console.log(list[i].code);    // 1 2
}

for-in

语法: for...in会以任意的顺序迭代一个对象的除symbol以外的可枚举属性,包括继承的可枚举属性 variable:每次迭代时,variable会被赋值为不同的属性名。 object:非sysbom类型的可枚举属性被迭代的对象

for (bariable in object)
 statement

for...in 不应该用于迭代一个关注索引顺序的Array。for...in是为了遍历对象的属性而构建的,此方法不建议和数组一起使用,数组可以用for...of和Array.prototype.forEach() for...in最常用于调试。可以更方便地去检查对象的任何键是否为某值。 (key-value类型数据)

var triangle = {a: 1, b: 2, c: 3};

function ColoredTriangle() {
 this.color = 'red';
}

ColoredTriangle.prototype = triangle;

var obj = new ColoredTriangle();

for (var prop in obj) {
 if (obj.hasOwnProperty(prop)) {
   console.log(`obj.${prop} = ${obj[prop]}`);
 }
}  // hasOwnProperty()的用法:继承的属性不显示

// Output:
// "obj.color = red"

for (var prop in obj) {
   console.log("obj." + prop + " = " + obj[prop]);
 }      
//   obj.color = red
// obj.a = 1
// obj.b = 2
// obj.c = 3

for...in遍历对象时使用break continue return for...in循环中不能使用return,会报错 for...in + break :可以使用,立即结束语句

var names = {name1: "第一", name2: "第二", name3: "第三", name4: "第四"}
 
for(var key in names) {
    if (names[key] === "第三") {
        break
    }
    console.log(names[key]) //第一 第二
}
console.log("下面代码");//下面代码

for...in + continue:可以使用,停止当前语句,继续下一次循环

var names = {name1: "第一", name2: "第二", name3: "第三", name4: "第四"}
 
for(var key in names) {
    if (names[key] === "第三") {
       continue;
    }
    console.log(names[key]) // 第一 第二 第四
}
console.log("下面代码"); // 下面代码

for...of

for...of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。

for (variable in iterable) {
    // statement
}

eg:迭代Array String TypedArray Map Set arguments对象

// 迭代Array
let iterable = [10, 20, 30];
for (let value of iterable) {
    value += 1;
    console.log(value);
}
// 11
// 21
// 31
如果不想修改语句块中的变量 , 可以使用const代替letlet iterable = [10, 20, 30];
for (const value of iterable) {
  console.log(value);
}
// 10
// 20
// 30


// String
let iterable = "boo";
for (let value of iterable) {
  console.log(value);
}
// "b"
// "o"
// "o"

// TypedArray
let iterable = new Uint8Array([0x00, 0xff]);
for (let value of iterable) {
  console.log(value);
}
// 0
// 255


Map
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (let entry of iterable) {
  console.log(entry);
}
// ["a", 1]
// ["b", 2]
// ["c", 3]
for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3


Set
let iterable = new Set([1, 1, 2, 2, 3, 3]);
for (let value of iterable) {
  console.log(value);
}
// 1
// 2
// 3

arguments对象
(function() {
  for (let argument of arguments) {
    console.log(argument);
  }
})(1, 2, 3);
// 1
// 2
// 3

for...in 和 for...of 的区别

Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};

let iterable = [3, 5, 7];
iterable.foo = 'hello';

for (let i in iterable) {
  console.log(i); //  0, 1, 2, "foo", "arrCustom", "objCustom"
}

for (let i in iterable) {
  if (iterable.hasOwnProperty(i)) {
    console.log(i); //  0, 1, 2, "foo"
  }
}

for (let i of iterable) {
  console.log(i); //  3, 5, 7
}

对于for...of循环,可以用break throw return来终止

function* foo(){
  yield 1;
  yield 2;
  yield 3;
};

for (let o of foo()) {
  console.log(o);
  break; // closes iterator, triggers return
}

let iterable = [3, 5, 7];
for (let i of iterable) {
    if (i == 5) {
        continue
    }
  console.log(i); // 3,  7
}

forEach

对数组的每个元素执行一次给定的函数 (按升序为数组中含有效值的每一项执行一次callback函数) 使用:

// 箭头函数
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// 回调函数
forEach(callbackFn)
forEach(callbackFn, thisArg)

// 内联回调函数
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* … */ })
forEach(function(element, index, array){ /* … */ })
forEach(function(element, index, array) { /* … */ }, thisArg)

参数
callbackFn
为数组中每个元素执行的函数。

函数调用时带有以下参数:
element
数组中正在处理的当前元素。
index
数组中正在处理的当前元素的索引。
array
forEach() 方法正在操作的数组。
thisArg 可选
可选参数。当执行回调函数 callbackFn 时,用作 this 的值。如果这个参数有值,则每次 callbackFn 函数被调用时,this 都会指向 thisArg 参数。如果省略了 thisArg 参数,或者其值为 null 或 undefined,this 则指向全局对象

forEach()被调用时,不会直接改变调用它的对象(即原数组),但原数组可能会被callbackfn函数改变。

除了抛出异常之外,没有办法终止或跳出forEach循环 forEach的回调中使用continue 或 break 报错

forEach + return :只是终止本次循环

const words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  if (word === 'two') {
    return   // 终止本次循环
  }
  console.log(word)   // one three four
}); 

forEach + continure (break)----  报错


正确用法:  try catch
try {
    var array = ["第一","第二","第三","第四"];
    
    // 执行到第3次,结束循环
    array.forEach(function(item,index){
        if (item == "第三") {
            throw new Error("第三");
        }
        console.log(item);// 第一 第二
    });
} catch(e) {
    if(e.message!="第三") throw e;
};
// 下面的代码不影响继续执行
console.log("下方代码");//下方代码


forEach 与 数组

const words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
  if (word === 'two') {
    words.shift(); //'one' 将从数组中删除
  }
}); // one // two // four

console.log(words); // ['two', 'three', 'four']