首页 > 解决方案 > 字符串数组随机删除3并替换为“”但保留原始索引

问题描述

    const state = reactive({    
      verify: [
        "brain",
        "show",
        "toy",
        "him",
        "aim",
        "built",
        "store",
        "there",
        "skim",
        "wing",
        "honest",
        "try",
      ],
    });

function remove(array: string[], numberOfDeletions: number) {
  array = state.array;
  for (var i = 0; i < numberOfDeletions; i++) {
    array.splice(Math.floor(Math.random() * array.length), 1);
  }
  console.log(array);
}
onMounted(async () => {
  const mnemonic = await removeRandomly(state.verify, 3);
});
function getWords(words: Array<string>) {
  state.mnemonicPhrase = words;
}

这是删除 3 个项目并替换为“”,但更改的索引被推送到最后 3 个索引我需要所有内容都保留在其原始索引中,我似乎无法弄清楚这里发生了什么

另请注意,如果输入为空以返回“”,我的 Vue 代码中有一个三元组来更改道具的值,因此我可以直观地看到它正在被删除

标签: javascriptarrays

解决方案


尝试这个

 for (var i = 0; i < numberOfDeletions; i++) {
    arr.splice(Math.floor(Math.random() * arr.length), 1,"");
  }

推荐阅读