1. 程式人生 > 程式設計 >JS陣列方法join()用法例項分析

JS陣列方法join()用法例項分析

本文例項講述了JS陣列方法join()用法。分享給大家供大家參考,具體如下:

join()方法

  1. 定義和用法:
    join() 方法用於把陣列中的所有元素放入一個字串。
    元素是通過指定的分隔符進行分隔的。
  2. 語法:arrayObject.join(separator)
  3. 引數:可選,指定要使用的分隔符。
    注:不給join()方法傳入任何值,或者給它傳入undefined,則使用逗號作為分隔符。
    IE7及更早版本會錯誤的使用字串“undefined”作為分隔符。
    陣列中的某一項是null或undefined,那麼該值在join()、toLocaleString()、toString()和valueOf()方法返回的結果中以空字串表示。
  4. 返回值:
    返回包含所有陣列項的字串。

程式碼如下:

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,6
console.log(arr.copyJoin().length); // 11
console.log(arr.copyJoin(undefined)); // 1,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,6,7,null,8,9];
console.log(arr2.copyJoin()); // 1,9
console.log(arr2.copyJoin().length); // 21
console.log(arr2.copyJoin(undefined)); // 1,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

感興趣的朋友可以使用線上HTML/CSS/JavaScript程式碼執行工具:http://tools.jb51.net/code/HtmlJsRun測試上述程式碼執行效果。

更多關於JavaScript相關內容感興趣的讀者可檢視本站專題:《JavaScript陣列操作技巧總結》、《JavaScript遍歷演算法與技巧總結》、《javascript面向物件入門教程》、《JavaScript數學運算用法總結》、《JavaScript資料結構與演算法技巧總結》及《JavaScript錯誤與除錯技巧總結》

希望本文所述對大家JavaScript程式設計有所幫助。