JS 将 forEach 变量传递给查找函数

JS passing the forEach variable to the lookup function

请帮助我理解如何将此参数传递给 formatter 的查找函数。我尝试为制表符动态创建 table 行:

有效:

keys = ["name", "price", "number"];
doAjax().then( variable => { 
    if ( products ) {
        let cols = [{title: "number", field: "number"}];
        keys.forEach(function ( key ) {
            let formatter = "";

            // check if key is number
            if ( key == "number" ) {
                formatter = function( cell ) {
                                return `<div íd="${key}">${cell.getValue()}</div>`;
                            };
            };
            cols.push({title: key, field: "data." + key, formatter: formatter});
         });
    };
 });    

不起作用:

let testf = function( cell, key ) { 
    return `<div íd="${key}">${cell.getValue()}</div>`; // key is not accessible here
};

keys = ["name", "price", "number"];
doAjax().then( variable => { 
    if ( products !== null ) {
        let cols = [{title: "number", field: "number"}];
        keys.forEach(function ( key ) {
            let formatter = "";

            // check if key is number
            if ( key == "number" ) {
                formatter = testf(cell, key);  // not working
            };
            cols.push({title: key, field: "data." + key, formatter: formatter});
         });
    };
 });    

上下文代码:

var table = new Tabulator("#products", {
    ajaxURL: "api/products",
    columns: cols,
});

我如何重写第二种方法,使其获得传递的参数键?

创建一个函数,将初始 cell 作为参数,并用它调用 testfkey.

if (key == "number") {
    formatter = cell => testf(cell, key);
};

只需将 key 作为第一个参数,然后绑定它:

let testf = function( key, cell ) { 
    return `<div íd="${key}">${cell.getValue()}</div>`; 
}

formatter = testf.bind(key);