将值附加到属性名称

Appending value to attribute name

我正在尝试为 JavaScript 模型设置属性。 我想为每个循环添加名称 logo0、logo1、logo2。 下面的代码片段行是错误的 logo+[i].

for (var i = 0; i <= paths.length - 1; i++) {
  Polygon.attr({
        logo+i: {
          d: paths[i],
          stroke: 'red',
          strokeWidth: "15",
          cursor: 'pointer',
          event: 'element:path-click',
          strokeLinecap: "square"
        }
      });
}

如何实现?

你可以使用计算的 属性 名称

只需将徽标 +i 包装在 []

我猜它看起来像 ["logo" + i]

在此处阅读更多内容

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

for (var i = 0; i <= paths.length - 1; i++) {
  Polygon.attr({
        ["logo"+i]: {
          d: paths[i],
          stroke: 'red',
          strokeWidth: "15",
          cursor: 'pointer',
          event: 'element:path-click',
          strokeLinecap: "square"
        }
      });
}

先创建对象,然后用方括号选择 logoX 属性:

for (var i = 0; i <= paths.length - 1; i++) {
    var attr = {};
    attr["logo"+i] = {
        d: paths[i],
        stroke: 'red',
        strokeWidth: "15",
        cursor: 'pointer',
        event: 'element:path-click',
        strokeLinecap: "square"
    };

    Polygon.attr(attr);
}

除了动态对象字面量的 computed property names 之外,您可以将 for 循环从

稍微更改一下
for (var i = 0; i <= paths.length - 1; i++) {
//                 ^              ^^^

for (var i = 0; i < paths.length; i++) {
    Polygon.attr({
        [logo + i]: {
            d: paths[i],
            stroke: 'red',
            strokeWidth: "15",
            cursor: 'pointer',
            event: 'element:path-click',
            strokeLinecap: "square"
        }
    });
}