【问题标题】:How to have a number in an array that can edit according to edits(removal or adding)如何在数组中有一个可以根据编辑进行编辑的数字(删除或添加)
【发布时间】:2021-02-04 23:33:50
【问题描述】:

对不起,标题解释得不好(真的不知道有什么其他的说法)。我有一个需要增量值的数组:

const array = [
  {
    name: 'charmander',
    iv: '13;10;25;24;4;21',
    lvl: 23,
    nature: 'Rash',
    holding: '',
    mega: false
  },
  {
    name: 'bulbasaur',
    iv: '19;18;13;20;27;28',
    lvl: 17,
    nature: 'Brave',
    holding: '',
    mega: false
  }
];

我想将数组映射到每个数组中都有一个数字的地方,例如:

const array = [
  {
    name: 'charmander',
    iv: '13;10;25;24;4;21',
    lvl: 23,
    nature: 'Rash',
    holding: '',
    mega: false,
    number: 1,
  }];

虽然,当我将内容添加到数组中时,我无法插入数字,因为它们可能会被删除或移除,从而留下数字间隙。有什么有效的方法吗?

【问题讨论】:

    标签: javascript arrays mapping increment


    【解决方案1】:
    // All your array initialization here
    
    // using simple cycle
    for (let i in array) {
      array[i].number = i;
    }
    
    // using foreach
    array.forEach((p, i) => { p.number = i; })
    
    // using map
    array = array.map((p, i) => { p.number = i; return p; });
    
    // dynamic association (if you later need to change the order)
    // this will automatically change if you sort your array or remove
    // some elements
    array.forEach(p => {
      Object.defineProperty(p, 'number', { get: () => array.indexOf(p) })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-08
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多