【问题标题】:How can I remove a index in the array on the javascript?如何删除 javascript 数组中的索引?
【发布时间】:2018-09-20 20:22:56
【问题描述】:

我的javascript代码是这样的:

<script type="text/javascript">
    var clubs = [ 
        {id: 1, name : 'chelsea'},
        {id: 2, name : 'city'},
        {id: 3, name : 'liverpool'}
    ];
    if(clubs.indexOf(2) != -1)
        clubs.splice(2, 1)
    console.log(clubs)
</script>

比如我要删除id=2的索引

我尝试这样,但它不起作用。 id = 2 的索引没有被删除

我该如何解决这个问题?

【问题讨论】:

标签: javascript jquery arrays object indexof


【解决方案1】:

这是解决您问题的方法,请检查:

var clubs = [
  { id: 1, name: 'chelsea' },
  { id: 2, name: 'city' },
  { id: 3, name: 'liverpool' }
];

for (var i = 0; i < clubs.length; i++) {
  if (clubs[i].id == 2) {
    clubs.splice(i, 1);
    break;
  }
}

console.log(clubs);

【讨论】:

  • 两种方式都可以。是的,使用严格类型更好。这不能成为投反对票的理由。大声笑。答案已编辑
  • 天啊。它的JavaScript。 .没关系。答案已编辑。感谢回复
【解决方案2】:

使用Array.filter

var clubs = [ 
        {id: 1, name : 'chelsea'},
        {id: 2, name : 'city'},
        {id: 3, name : 'liverpool'}
    ];

clubs = clubs.filter(function(item){
   return item.id !== 2;
});

console.log(clubs);

【讨论】:

  • @downvoter - 请给出原因?如果没有说明原因,投反对票有什么意义?
  • 为什么不指向许多重复的问题之一,而不是在这里重复一个解决方案? SO上有很多解决方案。
  • @nikhilagw 我认为这是建议的唯一体面的答案。我没有投反对票。但我认为H77是对的。
  • 这是最佳答案here。就像我说的......很多重复。没有理由添加更多。
  • @nikhilagw 太好了。有用。非常感谢。我接受你的回答,我投了赞成票。这对我有帮助:)
【解决方案3】:

由于您的 if 语句,该元素没有被删除,您正在检查 2 是否存在于数组中,但数组中没有像 2 这样的东西,因为它是一个对象数组。所以条件总是为假。

【讨论】:

    猜你喜欢
    • 2012-05-03
    • 2015-07-19
    • 2020-06-25
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2013-05-12
    相关资源
    最近更新 更多