Js数组是js知识中非常重要的一部分。有时候我们有这样的要求,js数组删除指定的元素。首先定义一个函数获取被删除的指定元素的索引值,然后使用js数组删除方法删除指定元素。两步走,不难,也简单。

   1.JS的array对象定义了一个函数来查找指定元素在数组中的位置,也就是索引值。代码如下:

   array . prototype . index of=function(val){ for(var I=0;我这.长度;i ) { if (this[i]==val)返回I;} return-1;};2.使用获取此元素的索引,并使用js数组的固有函数删除此元素。代码如下:

   array . prototype . remove=function(val){ var index=this . index of(val);if (index -1) { this.splice(index,1);} };这样就构造了这样一个js数组删除函数。

   3.Case:删除以下myCase数组中的“CD ”:

   var myCase=new Array(abk , djp , dcg , CD );您可以直接使用它:

   my case . remove( CD );4.最后

  验证js数组是否成功删除了指定的元素:

   console . log(my case[3]);我们可以在控制台中看到undefined是未定义的,表示数组的第四项已经被删除。

   5.案例完整版本的代码:

   script type= text/JavaScript array . prototype . index of=function(val){ for(var I=0;我这.长度;i ) { if (this[i]==val)返回I;} return-1;};array . prototype . remove=function(val){ var index=this . index of(val);if (index -1) { this.splice(index,1);} };var myCase=new Array(abk , djp , dcg , CD );my case . remove( CD );console . log(my case[3]);//打印结果:undefined/script