js筆記--高階函數array的各類函數

(1)every()方法能夠判斷數組的全部元素是否知足測試條件。數組

  例如,給定一個包含若干字符串的數組,判斷全部字符串是否知足指定的測試條件:函數

    var arr = ['Apple', 'pear', 'orange'];
    console.log(arr.every(function (s) {
      return s.length > 0;
    })); // true, 由於每一個元素都知足s.length>0測試

(2)find()方法用於查找符合條件的第一個元素,若是找到了,返回這個元素,不然,返回undefined網站

    var arr = ['Apple', 'pear', 'orange'];
    console.log(arr.find(function (s) {
      return s.toLowerCase() === s;
    })); // 'pear', 由於pear所有是小寫spa

(3)findIndex()find()相似,也是查找符合條件的第一個元素,不一樣之處在於findIndex()會返回這個元素的索引,若是沒有找到,返回-1code

    var arr = ['Apple', 'pear', 'orange'];
    console.log(arr.findIndex(function (s) {
      return s.toLowerCase() === s;
    })); // 1, 由於'pear'的索引是1索引

(4)forEach()map()相似,它也把每一個元素依次做用於傳入的函數,但不會返回新的數組。forEach()經常使用於遍歷數組,所以,傳入的函數不須要返回值:字符串

    var arr = ['Apple', 'pear', 'orange'];
    arr.forEach(console.log); // 依次打印每一個元素io

 

摘抄自廖雪峯老師的官方網站console

相關文章
相關標籤/搜索