總結一下工作當中經常使用的數組查找,遍歷等等

查找

find()函數用來查找目標元素,找到就返回該元素,找不到返回undefined

findIndex()函數也是查找目標元素,找到就返回元素的位置,找不到就返回-1

persons = [

    {

        name: '張三',

        gender: '男',

        age: 20

    },

    {

        name: '王小毛',

        gender: '男',

        age: 20

    },

    {

        name: '李四',

        gender: '男',

        age: 20

    }]

 

persons .find((element) => (element.name == '李四')); //返回的是{name: "李四", gender: "男", age: 20}這個元素

persons .findIndex((element)=>(element.name =='李四'));  //返回的是索引下標:2

 

遍歷

for…of (是es6標準,用來遍歷value值,遍歷數組,不能遍歷普通對象)

for...of 語句創建一個循環來迭代可迭代的對象。在 ES6 中引入的 for...of 循環,以替代 for...in 和 forEach() ,並支持新的迭代協議。for...of 允許你遍歷 Arrays(數組), Strings(字符串), Maps(映射), Sets(集合)等可迭代的數據結構等。

語法

for (variable of iterable) {

    statement

}

variable:每個迭代的屬性值被分配給該變量。

iterable:一個具有可枚舉屬性並且可以迭代的對象。

 

 

普通對象不可迭代

for...of 循環僅適用於迭代。 而普通對象不可迭代。 我們來看一下:

const obj = { fname: 'foo', lname: 'bar' };

 for (const value of obj) { // TypeError: obj[Symbol.iterator] is not a function

    console.log(value);

}

在這裏,我們定義了一個普通對象 obj ,並且當我們嘗試 for...of 對其進行操作時,會報錯:TypeError: obj[Symbol.iterator] is not a function。

 

我們可以通過將類數組(array-like)對象轉換爲數組來繞過它。該對象將具有一個 length 屬性,其元素必須可以被索引。我們來看一個例子:

// object-example.jsconst obj = { length: 3, 0: 'foo', 1: 'bar', 2: 'baz' };

 const array = Array.from(obj);for (const value of array) {

    console.log(value);

}// Output:// foo// bar// baz

Array.from() 方法可以讓我通過類數組(array-like)或可迭代對象來創建一個新的 Array(數組) 實例。

但是可以在新出來的對象類型上使用

var set = new Set();  

    set.add("a").add("b").add("d").add("c");  

    var map = new Map();  

    map.set("a",1).set("b",2).set(999,3);  

    for (let v of set) {  

        console.log(v);  

    }  

    console.log("--------------------");  

    for(let [k,v] of map) {  

        console.log(k,v);  

    }  

forEach

array.forEach(v=>{  

    console.log(v);  

});

array.forEach(function(v){  

    console.log(v);  

});

 

for in(for...in是es5標準,用來遍歷key值,遍歷對象和數組,但是一般不推薦遍歷數組)

遍歷對象

如果需要取得到數組或者對象的key值的時候可以使用for in

用for in不僅可以對數組,也可以對enumerable對象操作

var A = {a:1,b:2,c:3,d:"hello world"};  for(let k in A) {  

    console.log(k,A[k]);  

}

遍歷數組

var array = [1,2,3,4,5,6,7];

 

 for(let index in array) {  

        console.log(index,array[index]);  

    };

 

for in總是得到對像的key或數組,字符串的下標

for...in 循環主要是爲了遍歷對象而生,不適用於遍歷數組

for of和forEach一樣,是直接得到值
for of不能對對象使用

for...of 循環可以用來遍歷數組、類數組對象,字符串、Set、Map 以及 Generator 對象

for...in 循環不僅遍歷數字鍵名,還會遍歷手動添加的其它鍵,甚至包括原型鏈上的鍵。for...of 則不會這樣

 

無論是 for...in 還是 for...of 都不能遍歷出 Symbol 類型的值,遍歷 Symbol 類型的值需要用 Object.getOwnPropertySymbols() 方法

 

{

  let a = Symbol('a')

  let b = Symbol('b')

 

  let obj = {

    [a]: 'hello',

    [b]: 'world',

    c: 'es6',

    d: 'dom'

  }

 

  for(let key in obj) {

    console.info(key + ' --> ' + obj[key])

  }

 

  /*

    c --> es6

    d --> dom

  */

 

  let objSymbols = Object.getOwnPropertySymbols(obj)

  console.info(objSymbols)    //  [Symbol(a), Symbol(b)]

  objSymbols.forEach(item => {

    console.info(item.toString() + ' --> ' + obj[item])

  })

 

  /*

    Symbol(a) --> hello

    Symbol(b) --> world

  */

 

  // Reflect.ownKeys 方法可以返回所有類型的鍵名,包括常規鍵名和Symbol鍵名

  let keyArray = Reflect.ownKeys(obj)

  console.log(keyArray)      //  ["c", "d", Symbol(a), Symbol(b)]

}

原因是:普通對象沒有Symbol.iterator屬性,如果一個對象擁有Symbol.iterator屬性,那麼就可以使用for...of遍歷

// 下面的例子摘自 阮一峯老師的ES6入門第三版let obj = {

  data: [ 'hello', 'world' ],

  [Symbol.iterator]() {

    const self = this;

    let index = 0;

    return {

      next() {

        if (index < self.data.length) {

          return {

            value: self.data[index++],

            done: false

          };

        } else {

          return { value: undefined, done: true };

        }

      }

    };

  }}for (let value of obj) {

  console.log(value)}   // hello world// 類似數組的對象遍歷  直接引用Array.prototype[Symbol.iterator]  // 普通對象部署數組的Symbol.iterator方法,並無效果let iterable = {

  0: 'a',

  1: 'b',

  2: 'c',

  length: 3,

  [Symbol.iterator]: Array.prototype[Symbol.iterator]};for (let item of iterable) {

  console.log(item); // 'a', 'b', 'c'}

 

 

 

 

 

for...of 循環可以與break、continue 和 return 配合使用,跳出循環

 

for(let item of arr) {

   if(item % 2 === 0) {

     break

   }

   console.log('item', item)

 }

forEach 循環無法中途跳出,break 命令或 return 命令都不能奏效

let arr = [1, 2, 3, 5, 9]

arr.forEach(item => {

  if(item % 2 === 0) {

    return

  }

  console.log('item', item)

})

/*

  item 1

  item 3

  item 5

  item 9

*/

 

for...in 循環不僅遍歷數字鍵名,還會遍歷手動添加的其它鍵,甚至包括原型鏈上的鍵。for...of 則不會這樣

 let arr = [1, 2, 3]

arr.set = 'world'  // 手動添加的鍵

Array.prototype.name = 'hello'  // 原型鏈上的鍵

 

for(let item in arr) {

  console.log('item', item)

}

 

/*

  item 0

  item 1

  item 2

  item set

  item name

*/

 

for(let value of arr) {

  console.log('value', value)

}

 

/*

  value 1

  value 2

  value 3

*/

 

對於普通對象,沒有部署原生的 iterator 接口,直接使用 for...of 會報錯

var obj = {

   'name': 'Jim Green',

   'age': 12

 }

 

 for(let key of obj) {

   console.log('for of obj', key)

 }

 // Uncaught TypeError: obj is not iterable

可以使用 for...in 循環遍歷鍵名

for(let key in obj) {

   console.log('for in key', key)

 }

 /*

   for in key name

   for in key age

 */

也可以使用 Object.keys(obj) 方法將對象的鍵名生成一個數組,然後遍歷這個數組

for(let key of Object.keys(obj)) {

   console.log('key', key)

 }

 /*

   key name

   key age

 */

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章