JS数组方法加入()用法实例分析

  

本文实例讲述了JS数组方法加入()用法。分享给大家供大家参考,具体如下:

  

加入()方法

  
      <李>定义和用法:
      加入()方法用于把数组中的所有元素放入一个字符串。
      元素是通过指定的分隔符进行分隔的。   <李>语法:arrayObject.join(分隔符)   <李>参数:可选,指定要使用的分隔符。
      注:不给加入()方法传入任何值,或者给它传入没有定义,则使用逗号作为分隔符。
      IE7及更早版本会错误的使用字符串“定义”作为分隔符。
      数组中的某一项是零或未定义,那么该值在加入(),toLocaleString (), toString()和返回对象的值()方法返回的结果中以空字符串表示。   <李>返回值:
      返回包含所有数组项的字符串。   
  

代码如下:

        Array.prototype。copyJoin=function () {   var="字符串;   (var=0;我& lt;this.length;我+ +){//将数组中各项值为null或未定义的项改为空字符串。   如果(这[我]==null | |这[我]==定义){   [我]=";   }//对数组进行操作   如果参数。长度==1,,参数[0]!=未定义){//指定使用的分隔符   字符串+=(我& lt;这一点。长度- 1)& # 63;[我]+参数[0]:[我];   }   {//其他默认使用的分隔符——逗号//如果我& lt;这一点。长度- 1){//字符串+=[我]+ ',';//}//其他{//字符串+=(我);//}   字符串+=(我& lt;这一点。长度- 1)& # 63;这[我]+ " ":[我];   }   }   返回字符串;   }//不传任何值或者传入定义   var arr=[1, 2, 3, 4, 5, 6);   console.log (arr.copyJoin ());//1、2、3、4、5、6   console.log (arr.copyJoin () . length);//11   console.log (arr.copyJoin(定义));//1、2、3、4、5、6   console.log (arr.copyJoin(定义). length);//11//传入参数   console.log (arr.copyJoin (' | | '));//1 | | | 2 | 3 | 4 | | | 5 | | 6   console.log (arr.copyJoin (' | | ') . length);//16//数组中的某一项是null或定义   var arr2=[1,定义,2,定义,3,4,5,6,7,null, 8, null, 9];   console.log (arr2.copyJoin ());//1,2,3,4,5,6,7,8,9   console.log (arr2.copyJoin () . length);//21   console.log (arr2.copyJoin(定义));//1,2,3,4,5,6,7,8,9   console.log (arr2.copyJoin(定义). length);//21      之前      

运行结果:

  

 JS数组方法加入()用法实例分析

  

以上在IE8 +加入()方法一样,但是在IE7及更早版本(copyJoin()方法不存在):

        arr.join(定义));//1 undefined2undefined3undefined4undefined5undefined6   arr.join(定义). length);//51   arr2.join(定义));//1 undefinedundefined2undefinedundefined3undefined4undefined5undefined6undefined7undefinedundefined8undefinedundefined9   arr2.join(定义). length);//117      之前      

感兴趣的朋友可以使用:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。

  

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数组操作技巧总结》,《JavaScript遍历算法与技巧总结》,《JavaScript面向对象入门教程》、《JavaScript数学运算用法总结》,《JavaScript数据结构与算法技巧总结》及《JavaScript错误与调试技巧总结》

  

希望本文所述对大家JavaScript程序设计有所帮助。

JS数组方法加入()用法实例分析