lookupIndex [row [lookupKey]] = row;如何工作?

时间:2018-11-12 19:39:43

标签: javascript

我正在阅读learnjsdata.com,并遇到了这种陌生的JavaScript语法。语法如下:

lookupIndex[row[lookupKey]] = row;

有人知道这里发生了什么吗?我还没有看到这样的语法。在上下文中使用:

数据

var articles = [{
    "id": 1,
    "name": "vacuum cleaner",
    "weight": 9.9,
    "price": 89.9,
    "brand_id": 2
}, {
    "id": 2,
    "name": "washing machine",
    "weight": 540,
    "price": 230,
    "brand_id": 1
}, {
    "id": 3,
    "name": "hair dryer",
    "weight": 1.2,
    "price": 24.99,
    "brand_id": 2
}, {
    "id": 4,
    "name": "super fast laptop",
    "weight": 400,
    "price": 899.9,
    "brand_id": 3
}];

var brands = [{
    "id": 1,
    "name": "SuperKitchen"
}, {
    "id": 2,
    "name": "HomeSweetHome"
}];

功能和调用

function join(lookupTable, mainTable, lookupKey, mainKey, select) {
    var l = lookupTable.length,
        m = mainTable.length,
        lookupIndex = [],
        output = [];
    for (var i = 0; i < l; i++) { // loop through l items
        var row = lookupTable[i];
        lookupIndex[row[lookupKey]] = row; // create an index for lookup table
    }
    for (var j = 0; j < m; j++) { // loop through m items
        var y = mainTable[j];
        var x = lookupIndex[y[mainKey]]; // get corresponding row from lookupTable
        output.push(select(y, x)); // select only the columns you need
    }
    return output;
};

var result = join(brands, articles, "id", "brand_id", function(article, brand) {
    return {
        id: article.id,
        name: article.name,
        weight: article.weight,
        price: article.price,
        brand: (brand !== undefined) ? brand.name : null
    };
});

console.log(result);

感谢任何答案或指示,谢谢!

1 个答案:

答案 0 :(得分:2)

将其视为两个单独的函数调用:

var rowLookup = row[lookupKey];
lookupIndex[rowLookup] = row;

与在同一行中执行所有操作相同:

lookupIndex[row[lookupKey]] = row;