對於這個用例,@ 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]);
}
是,可以指定_rows_其移動到的參數,並與_bind_函數預先定義它 – Grundy