本文实例讲述了JS数组方法join()用法。分享给大家供大家参考,具体如下:
join()方法
代码如下:
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; } // 不传任何值或者传入undefined 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(undefined)); // 1,2,3,4,5,6 console.log(arr.copyJoin(undefined).length); // 11 // 传入参数 console.log(arr.copyJoin('||')); // 1||2||3||4||5||6 console.log(arr.copyJoin('||').length); // 16 // 数组中的某一项是null或undefined var 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,,9 console.log(arr2.copyJoin().length); // 21 console.log(arr2.copyJoin(undefined)); // 1,,2,,3,4,5,6,7,,8,,9 console.log(arr2.copyJoin(undefined).length); // 21
运行结果:
以上在IE8+ join()方法一样,但是在IE7及更早版本(copyJoin()方法不存在):
arr.join(undefined)); // 1undefined2undefined3undefined4undefined5undefined6 arr.join(undefined).length); // 51 arr2.join(undefined)); // 1undefinedundefined2undefinedundefined3undefined4undefined5undefined6undefined7undefinedundefined8undefinedundefined9 arr2.join(undefined).length); // 117
希望本文所述对大家JavaScript程序设计有所帮助。