我有一个字符串索引数组,我想从中删除一个项目.
请考虑以下示例代码:
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
Run Code Online (Sandbox Code Playgroud)
如何从第二个例子中删除"One",就像我在第一个例子中那样删除?
Pao*_*ino 20
执行此操作的正确方法不是使用Array而是使用对象:
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
Run Code Online (Sandbox Code Playgroud)
一旦Array具有字符串键(或不遵循的数字),它就变成了一个Object.
对象没有splice方法(或与Array不同).您必须编写自己的对象,通过创建一个新对象并将要保留的密钥复制到其中.
不过要小心 !这些键的排序方式并不总是与它们在对象中添加的方式相同!这取决于浏览器.