2011-09-02 80 views
1

即時通訊做上刪除陣列......因爲這是一個測試,這是相當非正式的代碼中的對象測試..在JavaScript數組刪除特定對象

<script type="text/javascript"> 

// initialize array and objects 
var fruits = new Array(); 

var z = { 
    test1: "test0", 
    test2: "test2" 
} 

fruits.push(z); 
var z2 = { 
    test1: "test1", 
    test2: "test2" 
} 
fruits.push(z2); 
var z3 = { 
    test1: "test2", 
    test2: "test2" 
} 
fruits.push(z3); 
var z4 = { 
    test1: "test3", 
    test2: "test2" 
} 
fruits.push(z4); 
var z5 = { 
    test1: "test4", 
    test2: "test2" 
} 
fruits.push(z5); 

// display array length 
document.write("array length is " + fruits.length + "<br>"); 

// traverse array 
for(var x = 0; x < fruits.length; x++){ 

    // display object content in array 
    document.write(fruits[x].test1 + " "); 

    // delete object in array where variable test1 is equal to "test2" 
    if(fruits[x].test1 == "test2"){ 
    fruits.splice(x, 1); 
    //document.write("array length is " + fruits.length + "<br>"); 
    } 
} 
</script> 

現在這個代碼工作正常(刪除數組上的一個對象),但它刪除一個我想要刪除的一個(在上面的代碼中,我想刪除索引2中的對象,但它刪除索引3中的對象)

任何我在這段代碼中做錯了嗎?

TIA :)

回答

0

這應該工作:

<script type="text/javascript"> 

    // initialize array and objects 
    var fruits = new Array(); 

    var z = { 
     test1: "test0", 
     test2: "test2" 
    } 

    fruits.push(z); 
    var z2 = { 
     test1: "test1", 
     test2: "test2" 
    } 
    fruits.push(z2); 
    var z3 = { 
     test1: "test2", 
     test2: "test2" 
    } 
    fruits.push(z3); 
    var z4 = { 
     test1: "test3", 
     test2: "test2" 
    } 
    fruits.push(z4); 
    var z5 = { 
     test1: "test4", 
     test2: "test2" 
    } 
    fruits.push(z5); 

    // display array length 
    document.write("array length is " + fruits.length + "<br>"); 

    // traverse array 
    for(var x = 0; x < fruits.length; x++){ 

     // display object content in array 
     document.write(fruits[x].test1 + " "); 

     // delete object in array where variable test1 is equal to "test2" 
     if(fruits[x].test1 == "test2"){ 
     fruits.splice(x-1, 1); 
     //document.write("array length is " + fruits.length + "<br>"); 
     } 
    } 
    </script> 
+0

感謝您的回答邁克:)不幸的是,我曾嘗試過這種解決方法,但它仍然沒有完成這項工作......你有其他的想法嗎?再次感謝:) – jason

6

你不應該嘗試在迭代它改變一個數組。相反,將要刪除的元素的索引保存在變量中,並在for循環之後將其刪除。

+0

做到了這一點:D非常感謝你:) – jason

0

使用在underscore.js '' 過濾器 '' 爲implemented

_.filter(fruits, function (fruit) { 
    return fruit.test1 !== "test2"; 
}); 

這具有使用快速的,原生的JavaScript方法( '' 過濾器 ''),其中可用的優勢。

+0

感謝您的迴應阿德里安,我也會嘗試這個解決方法:) – jason

相關問題