简体   繁体   English

如何在Javascript中同时从两端进行array.splice?

[英]How to array.splice from both ends simultaneously in Javascript?

How do you splice from both ends of an array either simultaneously or sequentially such that "leftsplice" number of fields are spliced from left and "rightsplice" number of fields are spliced from original array not the one after doing leftsplicing.您如何同时或顺序地从数组的两端拼接,以便从左侧拼接“leftsplice”数量的字段,并且从原始数组拼接“rightsplice”数量的字段,而不是在进行左拼接后拼接。 Any tips?有小费吗?

  const [skillname,setSkillName] = useState(["Engineering", "Product", "Organization", "Business", "Market", "Customer"]);
    setSkillName(skillname => skillname.splice(0,leftsplice))
    let temp=-5+leftsplice;
    setSkillName(skillname => skillname.splice(temp, rightsplice))

This is doing only leftsplicing.这只是做左拼接。 PS: leftsplice, rightsplice are working as desired. PS:leftsplice,rightsplice 可以正常工作。 I console.logged them我控制台记录了他们

Your code in splicing is okay, but you should only use setSkillName after both leftsplice and rightsplice is done by saving it on a temporary variable, I haven't tested this code below but it is answering the question "How to splice both at the same time from a state":您在拼接中的代码是好的,但你应该只在 leftsplice 和 rightsplice 都完成后使用setSkillName通过将它保存在一个临时变量上,我没有在下面测试这个代码,但它回答了问题“如何同时拼接两者一个状态的时间”:

function whatever() {
  let tempSkillName = [...skillname]
  tempSkillName = tempSkillName.splice(0,leftsplice))
  let temp=-5+leftsplice;
  tempSkillName = tempSkillName.splice(temp, rightsplice))
  setSkillName(tempSkillName)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM