拼接在JavaScript字符串数组索引 [英] Splicing a string indexed array in JavaScript

查看:176
本文介绍了拼接在JavaScript字符串数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

g·天所有,

我有一个字符串数组的索引,我想从删除项目。

I have a string indexed array that I would like to remove an item from.

考虑下面的例子code:

Consider the following example code:

    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

我如何从第二个例子删除一就像我在第一次做?

How do I remove "One" from the second example like I did in the first?

干杯,

迈克尔

推荐答案

要做到这一点,正确的方法是不是一个数组,但一个对象:

The proper way to do this is not with an Array but an object:

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

这篇关于拼接在JavaScript字符串数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆