2009-06-04 37 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