2016-11-21 42 views
0

我正嘗試使用的forEach拉姆達一個對象中設置一些值:拉姆達的語法正確的JavaScript

var row = {title: "", attribute:"", width: ""}; 
list.forEach(list => 
       row.title = list.label | 
       row.attribute = list.label | 
       row.width = "300px"  
      ); 

做工精細只聲明row.title = list.label當我添加的參數,其餘不正常工作。

什麼是正確的語法?

+0

請注意,術語「lambda」實際上從未在JavaScript中使用過。在JS中,「lambda」被稱爲「匿名函數」。 – JJJ

+1

我認爲它被稱爲_arrow function_。 – frhd

+2

你嘗試過{{}嗎?請參閱https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Satpal

回答

4

嘗試:

​​

注意花括號。

3

你需要花括號,作爲=>之後的部分是函數體:

var row = {title: "", attribute:"", width: ""}; 
list.forEach(list => { 
    row.title = list.label; 
    row.attribute = list.label; 
    row.width = "300px"; 
}); 

(注意,如果這是你實際運行的代碼,在row值將被設置爲在列表中的最後一項的值)

0

你應該換不回來的箭頭函數語句用大括號:

var list = [ 
 
    { label: 'one' }, 
 
    { label: 'two' }, 
 
    { label: 'three' } 
 
]; 
 

 
var row = {title: "", attribute:"", width: ""}; 
 

 
list.forEach(list => { 
 
    row.title = list.label; 
 
    row.attribute = list.label; 
 
    row.width = "300px"; 
 
}); 
 

 
console.log('Row is', row);

0

因爲它的立場row將持有每個.forEach的循環的數據,所以你只會獲取最後處理的元素的數據。你想創建一個新對象來存儲這些循環的每一個數據,然後有一個填充數組。

var Row = (title, attribute, width) => { 
    this.title = title; 
    this.attribute = attribute; 
    this.width = width; 
}; 

var rows = []; 
list.forEach(item => { 
    rows.push(new Row(list.label, list.label, "300px")); 
}); 

另外,該map功能可以做你更少的代碼想要的東西。

var rows = list.map((item) => { 
    return new Row(item.label, item.label, "300px"); 
});