您好,登錄后才能下訂單哦!
本文實(shí)例講述了JS數(shù)組方法join()用法。分享給大家供大家參考,具體如下:
join()方法
代碼如下:
Array.prototype.copyJoin = function() { var string = ''; for(var i = 0; i < this.length; i++) { // 將數(shù)組中各項(xiàng)值為null 或undefined的項(xiàng)改為空字符串。 if(this[i] == null || this[i] == undefined) { this[i] = ''; } // 對數(shù)組進(jìn)行操作 if(arguments.length == 1 && arguments[0] != undefined) { //指定使用的分隔符 string += (i < this.length - 1) ? this[i] + arguments[0] : this[i]; } else { // 默認(rèn)使用的分隔符————逗號 // 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 // 傳入?yún)?shù) console.log(arr.copyJoin('||')); // 1||2||3||4||5||6 console.log(arr.copyJoin('||').length); // 16 // 數(shù)組中的某一項(xiàng)是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
運(yùn)行結(jié)果:
以上在IE8+ join()方法一樣,但是在IE7及更早版本(copyJoin()方法不存在):
arr.join(undefined)); // 1undefined2undefined3undefined4undefined5undefined6 arr.join(undefined).length); // 51 arr2.join(undefined)); // 1undefinedundefined2undefinedundefined3undefined4undefined5undefined6undefined7undefinedundefined8undefinedundefined9 arr2.join(undefined).length); // 117
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運(yùn)行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript數(shù)組操作技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》、《javascript面向?qū)ο笕腴T教程》、《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。