【问题标题】:Delete elements in one array by using indices of second array [closed]使用第二个数组的索引删除一个数组中的元素[关闭]
【发布时间】:2017-09-20 16:20:58
【问题描述】:

1) 取一个数组 a = [a,b,c,d,e,f,g,h,i,j]; //通过 JavaScript 实现的实际数组

2)通过html标签//b数组获取5个数字的输入数组'b'

3) 'b' 的输入元素,使其始终小于 'a' 数组的长度。

4) 现在从'a' 中删除索引值为'b' 的所有值

5) 现在打印新的'a' 数组。

  1. 示例:a=[23,45,5,6,3,3,5,8,97,10]
  2. b=[3,4,6,7,2]
  3. new a array=[23,3,97,10,8,9]
  4. 现在数组 1 中的所有元素都被删除了 b 的元素。
  5. a[3],a[4],a[6],a[7],a[2] 已被删除(请勿打扰数组索引)。

【问题讨论】:

  • 为什么5 在结果数组中?
  • @guest271314 是的,我应该删除它。现在很好
  • 我们可以看看你的尝试吗,OP?这看起来像是免费工作的请求。
  • 你忘了问问题。英语中的问题用问号?表示,可以得到答案。照原样,这篇文章是一个纯粹的家庭作业转储。请阅读本网站上的How to Ask,以及what topics you can ask about here
  • 为什么9 在结果集中?为什么108 之前出现?如果从 10 个项目中删除 5 个,为什么会得到 6 个项目?

标签: javascript html arrays splice


【解决方案1】:

改用filter

a = a.filter( function(item, index){ //iterate the array a
  return b.indexOf(index+1) == -1; //removing those items whose index is not in the index array b. index-array b has 1-based indexes as per your example
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2017-02-25
    相关资源
    最近更新 更多