remove entry from javascript array - Stack Overflow

I have created an array:myarray = new Array();myarray['test_a'] = "test a";myarra

I have created an array:

myarray = new Array();
myarray['test_a'] = "test a";
myarray['test_b'] = "test b";

Now I would like to remove the entry with index "test_b". I tried this way:

var del = "test_b";
for(key in myarray){
   if(key==del){
      myarray.splice(key,1);
   }
}

However it does not work. No error. I just checked in firebug the entries for the array and mentioned that "test_b" still exists. What is wrong? Thanks for help.

I have created an array:

myarray = new Array();
myarray['test_a'] = "test a";
myarray['test_b'] = "test b";

Now I would like to remove the entry with index "test_b". I tried this way:

var del = "test_b";
for(key in myarray){
   if(key==del){
      myarray.splice(key,1);
   }
}

However it does not work. No error. I just checked in firebug the entries for the array and mentioned that "test_b" still exists. What is wrong? Thanks for help.

Share Improve this question asked Oct 3, 2013 at 2:47 zulukzuluk 1,5778 gold badges30 silver badges53 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Arrays are meant to have numeric indices, you want an object, then you can simply use delete:

var obj = {};
obj.test_a = "test a";
obj.test_b = "test b";

var del = "test_b";
delete obj[del];

console.log(obj); //=> { test_a: "test_a" }

splice works on numerical index, what you have is that you have added a property to the array object. You can just do a delete to delete the property from the array object.

  delete myarray[del];

Demo

if you are just defining properties on an array and using it just as an object then better consider using an object instead of creating an array to store properties

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745411519a4626554.html

相关推荐

  • remove entry from javascript array - Stack Overflow

    I have created an array:myarray = new Array();myarray['test_a'] = "test a";myarra

    4小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信