2016-07-20 38 views
-1

我想在这一个项目已经使用后切片的数组,但代码不这样做:切片在JavaScript数组

vm.removeItem = function() { 
    for(let i = 0; i < vm.array.length; i++) { 
    if(vm.array[i].item === vm.item) { 
     vm.array.splice(i, 1); 
     break; 
    } 
    } 
}; 

有什么事我做不正确的?

+1

这是否必须标记angularjs ? –

+0

@CrescentFresh,doesnt havet,但我反正用它思考我在Angular和JS的新手 – John

+0

vm是什么?你想要切掉什么物品?该函数不带参数,所以我只能假设第一个或最后一个元素。但是如果是这样的话,就不需要for循环。 –

回答

0

假设假码。要移除的项目存储在项目中。 removeItem被调用后,其被删除。

var vm = { 
 
    array: [{ 
 
    lp: 1 
 
    }, { 
 
    lp: 2 
 
    }, { 
 
    lp: 3 
 
    }], 
 
    item: 2 
 
}; 
 

 
vm.removeItem = function() { 
 
    for (let i = 0; i < vm.array.length; i++) { 
 
    if (vm.array[i].lp === vm.item) { 
 
     vm.array.splice(i, 1); 
 
     break; 
 
    } 
 
    } 
 
}; 
 

 
vm.removeItem(); 
 
console.log(vm.array);

+0

@John请检查这个代码,这是你在找什么?我试图创建一个虚拟代码来使其可行。 – Ayan

0

根据现有的代码,它看起来像你的vm结构看起来像这样:

var vm = { 
    item: 'ef', 
    array: [ {item: 'ab'}, {item : 'cd'}, {item: 'ef'}, {item: 'gh'} ] 
}; 

如果你想从vm.array删除其item属性是vm.item元素,你可以这样做:

vm.array = vm.array.filter(function(e) { return e.item != vm.item; }); 

但是,我认为您的代码应该按预期方式工作,并执行完全相同的事情。所以,问题可能在其他地方。

0

这可能是Remove a particular element from an array in JavaScript?

重复不管怎么说,你总是可以做这样的事情:

function remove(arr, item) { 
    for(var i = arr.length; i--;) { 
    if(arr[i] === item) { 
     arr.splice(i, 1); 
    } 
    } 
} 

而这里的用法:

// an array 
var entries = [ 
    {name:'Tim'}, 
    {name:'John'} 
]; 
// add an item to the array 
var mark = {name:'Mark'}; 
entries.push(mark); 

// you can see it's in the array now 
entries.forEach(x => console.log(x.name)); 

// remove it from the array 
remove(entries,mark); 

// you can see it's not there now 
entries.forEach(x => console.log(x.name));