2009-06-04 77 views
7

我有一個字符串索引數組,我想從中刪除一個項目。在JavaScript中拼接字符串索引數組

考慮下面的示例代碼:

var arr = new Array();  
    arr[0] = "Zero"; 
    arr[1] = "One"; 
    arr[2] = "Two"; 
    arr.splice(1, 1); 

    for (var index in arr) 
     document.writeln(arr[index] + " "); 

    //This will write: Zero Two 

    var arr = new Array(); 
    arr["Zero"] = "Zero"; 
    arr["One"] = "One"; 
    arr["Two"] = "Two"; 

    arr.splice("One", 1); //This does not work 
    arr.splice(1, 1); //Neither does this 

    for (var index in arr) 
     document.writeln(arr[index] + " "); 

    //This will write: Zero One Two 

如何從第二個例子刪除「一」就像我在第一次做?

+0

可能重複[查找字符串中的所有正則表達式匹配模式和匹配指數(HTTP://計算器。 com/questions/6178335/find-all-matching-regex-patterns-and-index-of-the-string) – Gajus 2015-09-13 20:09:00

回答

20

正確的方式做,這是不是一個數組,但對象:中

var x = {}; 
x['Zero'] = 'Zero'; 
x['One'] = 'One'; 
x['Two'] = 'Two'; 
console.log(x); // Object Zero=Zero One=One Two=Two 
delete x['One']; 
console.log(x); // Object Zero=Zero Two=Two 
+1

對數組也可以很好地工作:https://jsfiddle.net/6abLj89b/。 – Daniel 2017-02-14 09:18:55

4

一旦數組有字符串鍵(或不遵循的數字),它就成爲一個對象。

一個對象沒有拼接方法(或不同於Array)。您必須編寫自己的程序,方法是製作一個新對象,並將其保留爲要複製的密鑰。

但要小心!鑰匙並不總是按照它們添加到物體的相同方式排列!這取決於瀏覽器。

+0

不正確:https://jsfiddle.net/ycooo187/。 – Daniel 2017-02-14 09:12:56