JS数组方法join()用法实例分析
前端  /  管理员 发布于 7年前   298
本文实例讲述了JS数组方法join()用法。分享给大家供大家参考,具体如下: join()方法 代码如下: 运行结果: 以上在IE8+ join()方法一样,但是在IE7及更早版本(copyJoin()方法不存在): 感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools..net.cn/code/HtmlJsRun测试上述代码运行效果。 更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数组操作技巧总结》、《JavaScript遍历算法与技巧总结》、《javascript面向对象入门教程》、《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript错误与调试技巧总结》 希望本文所述对大家JavaScript程序设计有所帮助。
join() 方法用于把数组中的所有元素放入一个字符串。
元素是通过指定的分隔符进行分隔的。
注:不给join()方法传入任何值,或者给它传入undefined,则使用逗号作为分隔符。
IE7及更早版本会错误的使用字符串“undefined”作为分隔符。
数组中的某一项是null或undefined,那么该值在join()、toLocaleString()、toString()和valueOf()方法返回的结果中以空字符串表示。
返回包含所有数组项的字符串。Array.prototype.copyJoin = function() { var string = ''; for(var i = 0; i < this.length; i++) { // 将数组中各项值为null 或undefined的项改为空字符串。 if(this[i] == null || this[i] == undefined) { this[i] = ''; } // 对数组进行操作 if(arguments.length == 1 && arguments[0] != undefined) { //指定使用的分隔符 string += (i < this.length - 1) ? this[i] + arguments[0] : this[i]; } else { // 默认使用的分隔符――――逗号 // if(i < this.length - 1) { // string += this[i] + ','; // } // else { // string += this[i]; // } string += (i < this.length - 1) ? this[i] + ',' : this[i]; } } return string;}// 不传任何值或者传入undefinedvar arr = [1, 2, 3, 4, 5, 6];console.log(arr.copyJoin()); // 1,2,3,4,5,6console.log(arr.copyJoin().length); // 11console.log(arr.copyJoin(undefined)); // 1,2,3,4,5,6console.log(arr.copyJoin(undefined).length); // 11// 传入参数console.log(arr.copyJoin('||')); // 1||2||3||4||5||6console.log(arr.copyJoin('||').length); // 16// 数组中的某一项是null或undefinedvar arr2 = [1, undefined, 2, undefined, 3, 4, 5, 6, 7, null, 8, null, 9];console.log(arr2.copyJoin()); // 1,,2,,3,4,5,6,7,,8,,9console.log(arr2.copyJoin().length); // 21console.log(arr2.copyJoin(undefined)); // 1,,2,,3,4,5,6,7,,8,,9console.log(arr2.copyJoin(undefined).length); // 21
arr.join(undefined)); // 1undefined2undefined3undefined4undefined5undefined6arr.join(undefined).length); // 51arr2.join(undefined)); // 1undefinedundefined2undefinedundefined3undefined4undefined5undefined6undefined7undefinedundefined8undefinedundefined9arr2.join(undefined).length); // 117
您可能感兴趣的文章:
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号