首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >‘`lookupIndex[row[lookupKey]] =row;’是如何工作的?

‘`lookupIndex[row[lookupKey]] =row;’是如何工作的?
EN

Stack Overflow用户
提问于 2018-11-12 19:39:42
回答 1查看 34关注 0票数 0

我正在阅读learnjsdata.com,并偶然发现了一个不熟悉的JavaScript语法。语法如下:

lookupIndex[row[lookupKey]] = row;

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

数据

代码语言:javascript
复制
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"
}];

函数&调用

代码语言:javascript
复制
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);

感谢你的回答和建议,谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-12 19:50:00

把它看作是两个单独的函数调用:

代码语言:javascript
复制
var rowLookup = row[lookupKey];
lookupIndex[rowLookup] = row;

这和在同一条线上做这一切是一样的:

代码语言:javascript
复制
lookupIndex[row[lookupKey]] = row;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53268992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档