javascript ES6 - 使用`...`扩展运算符来修改/拼接/合并具有obects的数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript ES6 - 使用`...`扩展运算符来修改/拼接/合并具有obects的数组相关的知识,希望对你有一定的参考价值。

  
  const marvel = [
    { id: 4943, hero: 'Captain Marvel' },
    { id: 9854, hero: 'Luke Cage' },
    { id: 3943, hero: 'Iron Man' },
    { id: 1209, hero: 'Daredevil' },
    { id: 6592, hero: 'Mr. Fantastic' },
  ];
  
    
  const dc = [
    { id: 4943, hero: 'Batman' },
    { id: 9854, hero: 'Green Lantern' },
    { id: 3943, hero: 'Superman' },
    { id: 1209, hero: 'The Flash' },
    { id: 6592, hero: 'Aquaman' },
  ];
  
  // We've got a hero turned bad in our object, this is their id:
  const badHeroId = 3943;
  // With findIndex we can easily get the object index based on the ID
  const badHeroIndex = marvel.findIndex(hero => hero.id === badHeroId);
  // We use the index to slice the array twice: One time to get all the heroes from
  // 0 up to the bad hero, the second one to get all the heroes from the index after the 
  // bad hero up until the end (no argument); We immediately spread these out into the 
  // `newHeroes` array. 
  const newHeroes = [...marvel.slice(0, badHeroIndex), ...marvel.slice(badHeroIndex + 1)];
  console.log(newHeroes);
  
  // Now we'd love to combine some Marvel and DC superheroes into a new team:
  const marvelDC = [...marvel.slice(0, 3), ...dc.slice(3)];
  console.log(marvelDC)
  
  

以上是关于javascript ES6 - 使用`...`扩展运算符来修改/拼接/合并具有obects的数组的主要内容,如果未能解决你的问题,请参考以下文章

javascript JavaScript滚动到ID - 使用ES6类

ES6语法基本使用

javascript 返回顶部 - 使用ES6类

JavaScript ES6 项目和 jQuery

javascript 常见问题 - 使用ES6类

为啥我不能在 JavaScript/ES6 中使用带有箭头函数的`new`? [复制]