2010-01-28 68 views
2

我的問題是,我不得不從數組中刪除一些東西。我發現如何從列表框中刪除某些內容。但問題是,列表框由一個數組填充。所以如果我不刪除數組中的值(我從列表框中刪除)。當您添加新項目時,該值會不斷返回。順便說一句:我是新來的PHP和JavaScript。如何從數組中刪除某些內容?

我的代碼是:

function removeItem(veldnaam){ 
var geselecteerd = document.getElementById("lst"+veldnaam).selectedIndex; 
var nieuweArray; 
alert(geselecteerd);  
alert(document.getElementById(veldnaam+'hidden').value); 

For (var i = 0, i<= arr.lenght, i++) { 
If (i= geselecteerd){ 
    nieuweArray = arr.splice(i,1); 
    document.getElementById(veldnaam+'hidden').value = arr; 
       }} 

document.getElementById("lst"+veldnaam).remove(geselecteerd); 
    } 
+0

那些荷蘭語標識符聽起來很有趣 - 我推薦只使用英語,尊重編碼習慣......:D – Gnark 2010-01-28 08:43:39

+0

kk謝謝你的建議大二 – stijn 2010-01-28 08:45:58

回答

0
var geselecteerd = document.getElementById("lst"+veldnaam).selectedIndex; 
var nieuweArray; 
var teller = 0; 
var oudeArray=document.getElementById(veldnaam+'hidden').value; 
var tmpArr=""; 


nieuweArray=oudeArray.split(":"); 

for (i = 0; i<nieuweArray.length; i++){ 
if (!(i==geselecteerd)){ 
tmpArr = tmpArr+nieuweArray[i]+":";} 
teller++; 
} 
tmpArr = tmpArr + ":"; 
tmpArr = tmpArr.replace("::",""); 
document.getElementById(veldnaam+'hidden').value = tmpArr;   
document.getElementById("lst"+veldnaam).remove(geselecteerd); 
} 

這是我的解決方案,它的工作。謝謝你的幫助。

3

使用delete運算符。我假設你使用對象作爲關聯數組。

var arr = { 
    "hello": "world", 
    "foo": "bar" 
} 
delete arr["foo"]; // Removes item with key "foo" 
+2

刪除arr.foo也應該工作。 – Alex 2010-01-28 08:23:48

+2

stijn使用'arr.splice()',所以我認爲你假設錯誤。在* true *數組中,'delete'運算符不會更改索引... – Boldewyn 2010-01-28 08:41:15

3

可以刪除使用刪除命令數組中的元素。但它只會將值設置爲undefined

var arr = ['h', 'e', 'l', 'l', 'o']; 
delete arr[2]; 

arr => ['h', 'e', undefined, 'l', 'o']; 

所以不會刪除該項目,並進行了更短的陣列,所述陣列將仍然有5個元素(0〜4),但該值已被刪除。

在「關聯」數組或對象的情況下:該屬性將被擦除並且不再存在。

var obj = { 'first':'h', 'second':'e', 'third':'l'}; 
delete obj['first']; 

obj => { 'second':'e', 'third':'l'}; 
3

添加以下代碼某處


// Array Remove - By John Resig (MIT Licensed) 
Array.prototype.remove = function(from, to) { 
    var rest = this.slice((to || from) + 1 || this.length); 
    this.length = from < 0 ? this.length + from : from; 
    return this.push.apply(this, rest); 
}; 

,並調用它像這樣:


// Remove the second item from the array 
array.remove(1); 
// Remove the second-to-last item from the array 
array.remove(-2); 
// Remove the second and third items from the array 
array.remove(1,2); 
// Remove the last and second-to-last items from the array 
array.remove(-2,-1); 

包含上面的代碼條和解釋:http://ejohn.org/blog/javascript-array-remove/