如何删除 javascript 数组中的索引?
How can I remove a index in the array on the javascript?
我的 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的索引没有被删除
我该如何解决这个问题?
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);
由于您的 if 语句,该元素未被删除,您正在检查 2
是否存在于数组中,但数组中没有像 2 这样的东西,因为它是一个对象数组。所以条件始终为假。
这是解决您的问题的方法,请查看:
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 代码是这样的:
<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的索引没有被删除
我该如何解决这个问题?
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);
由于您的 if 语句,该元素未被删除,您正在检查 2
是否存在于数组中,但数组中没有像 2 这样的东西,因为它是一个对象数组。所以条件始终为假。
这是解决您的问题的方法,请查看:
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);