2015-12-16 30 views
0

如果我有這樣的代碼:傳遞Array.prototype中「for each」循環的參數的語法是什麼?

QB_list.x.forEach(pushElementsQB) 

function pushElementsQB(element, index, array) 
{ 
    rows.push([element, QB_list.y[index], "QB: " + QB_list.text[index], null, null, null, null]); 
} 

有沒有指定我的回調行變量的方法嗎?我是新來的JavaScript和看spec不工作對我來說這時間:/

+0

是,可以指定_rows_其移動到的參數,並與_bind_函數預先定義它 – Grundy

回答

1

正如@Grundy提到,這樣做的一個方法是用綁定的這個值設置在函數內部:

QB_list.x.forEach(pushElementsQB.bind(rows)) 

function pushElementsQB(element, index, array) // here this will be rows 
{ 
    this.push([element, QB_list.y[index], "QB: " + QB_list.text[index], null, null, null, null]); 
} 

這是與設置的foreach第二個參數:

QB_list.x.forEach(pushElementsQB, rows) 

另一種方式也將是隻需添加行作爲一個額外的參數:

QB_list.x.forEach(pushElementsQB.bind(QB_list.x.forEach.args,rows)) 

然後用:

function pushElementsQB(rows, element, index, array) // be careful, rows is the first parameter now 
{ 
    rows.push([element, QB_list.y[index], "QB: " + QB_list.text[index], null, null, null, null]); 
} 
+0

還可以加入樣品,其中行綁定作爲在這種情況下參數 – Grundy

+0

也代替_bind_可能使用第二個參數爲_forEach_ – Grundy

+0

@Grundy是真的有很多方法。增加了一些,謝謝 – juvian

3

爲什麼不直接使用map

var rows = QB_list.x.map(pushElementsQB); 

function pushElementsQB(element, index, array) 
{ 
    return [element, QB_list.y[index], "QB: " + QB_list.text[index], null, null, null, null]; 
} 

map本質上是一個forEach它返回一個Array

1

對於這個用例,@ Mathletics的Map答案是最好的,但要回答這個問題,並擴展到@juvian和@ Grundy的迴應。您可以使用綁定來綁定上下文(this關鍵字)。然而,這是非常糟糕的,因爲你讓該函數採用該上下文,以及那些參數永遠,以及所有其他用法直到解除綁定。

您可以按如下所示以更簡單,更安全以及更期待的方式進行此操作。

Array.forEach的第二個參數是thisArg。給這個行,並且它沒有使用綁定就完成了。

var rows = []; // Declare rows variable 
QB_list.x.forEach(pushElementsQB, rows) // Pass it in for the callbacks context 

function pushElementsQB(element, index, array) { 
    this.push([element, QB_list.y[index], "QB: " + QB_list.text[index], null, null, null, null]); 
} 

如果你真的想將變量徵收到的參數,你可以這樣做:

var rows = []; // Declare rows variable 
QB_list.x.forEach(function() { 
    pushElementsQB.apply(
     QB_list.x, // Set the function to be called with list as context (`this`) 
     arguments.concat([rows]) // Grab the arguments to this function, append rows, set the function to be called with that appended list 
    ) 
}) 

function pushElementsQB(element, index, array, rows) { 
    // Rows is appended to the end of the arguments list, so, maps to 'rows' argument here 
    rows.push([element, QB_list.y[index], "QB: " + QB_list.text[index], null, null, null, null]); 
} 
1

map,由Mathletics建議是不錯的選擇。使用它的另一個好的理由是你可以在回調中傳入一個初始參數,作爲this。例如,如果rows已經聲明,並要推動更多的數據,那麼你可以做類似如下:

var data = { x: [1, 2, 3, 4] }; 
var rows = [2]; 

// pass in `rows` as the initial argument 
data.x.map(pushElementsQB, rows); 

function pushElementsQB(el) { 

    // `this` is `rows`, and `map` appends the elements 
    // from data.x to it. 
    return this.push(el); 
} 

console.log(rows); // [2, 1, 2, 3, 4] 

整齊漂亮。

DEMO

+0

不僅地圖允許'this'。 –

+0

如果你沒有對結果數組IMO做任何事情,使用'map'也是很奇怪的。 – Mathletics