JavaScript 五四三 Ep.08 Array.prototype.join()


Posted by ABow_Chen on 2022-10-07

一、join() 簡介

  1. join() 方法會將陣列(或一個類陣列物件 array-like)中的所有元素連結、合併成一個字串,並將此字串回傳。

二、join() 語法

arr.join([separator])

separator(選擇性):

  • 用來隔開陣列中每個元素的字串。
  • 如果未傳入此參數,陣列中的元素預設用英文逗號「,」隔開。
  • 如果為負數,則會從陣列最後一個數值往回算(從右至左),陣列中最後一個值為之索引為 -1。
  • 如果 separator 為空字串,合併後,元素間不會有任何字元。

語法的執行範例如下:

const words = ['a', 'b', 'c'];

console.log(words.join()); // a,b,c
console.log(words.join('')); // abc

三、join() 常見用法、情境

  1. 傳入不同的 separator

     const uniqueSkill = ['歐拉', '歐拉', '歐拉', '歐拉', '歐拉', '!!!'];
    
     console.log("白金之星:"+uniqueSkill.join()); // 白金之星:歐拉,歐拉,歐拉,歐拉,歐拉,!!!
     console.log("白金之星:"+uniqueSkill.join(''));  // 白金之星:歐拉歐拉歐拉歐拉歐拉!!!
     console.log("白金之星:"+uniqueSkill.join('!')); // 白金之星:歐拉!歐拉!歐拉!歐拉!歐拉!!!!
    
  2. 在類陣列上使用

     function joinFn(a, b, c){
       let string = Array.prototype.join.call(arguments);
       console.log(string);
     }
     joinFn(1, 'a', true); // 1,a,true
    

參考資料:

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/join


#javascript #join







Related Posts

[keybr]_Day04

[keybr]_Day04

Modern Web 2018 簡短心得

Modern Web 2018 簡短心得

Demystifying Stubs in IT: A Comprehensive Exploration of IT Stubs

Demystifying Stubs in IT: A Comprehensive Exploration of IT Stubs


Comments