2017-09-16 86 views
0

如何使用箭頭函數縮短語法...?Javascript arrow功能而不是...

  this.id = 1;     
      let products: Product[] = [ 
       { 
        "id": 1, 
        "name": "Bycicle" 
       }, 
       { 
        "id": 2, 
        "name": "iPhoneX" 
       } 
      ]; 


     for (let p of products) { 
      if (p.id == this.id) { 
       this.product = p; 
       break; 
      } 
     } 

最後一塊可以寫成單行嗎?我試過,但它看起來真的錯了:

this.product = products.filter(p => p.id == this.id)[0]; 

我在.NET中尋找類似.FirstOrDefault

回答

2

使用Array#find

this.product = products.find(p => p.id === this.id) 

爲了得到一個相當於firstOrDefault,你可以短路結果

this.product = products.find(p => p.id === this.id) || {} 
+0

這是確定的,但我忘了告訴大家,我用的打字稿(因爲Angular2的),所以我得到的當我使用||時,在第二個答案中出錯{}「類型{}不能分配給類型Product ...」 – Dalibor

+0

...但我設法用||來解決它。新產品() – Dalibor

2

find應該做

this.product = products.find(p => p.id === this.id); 

DEMO

let id =1; 
 
var products = [ 
 
       { 
 
        "id": 1, 
 
        "name": "Bycicle" 
 
       }, 
 
       { 
 
        "id": 2, 
 
        "name": "iPhoneX" 
 
       } 
 
      ]; 
 
      
 
let product = products.find(p => p.id === id); 
 
console.log(product);