B-Teck!

お仕事からゲームまで幅広く

【JavaScript】クリップボードに文字列をコピーする

document.execCommand("copy") が選択した要素の文字列のみしかコピー出来ないので、
一時的に要素を作って、選択してコピーする。

const copyToClipboard = s => {
    const d = document;
    // copy用の一時要素を作成し、文字を入れる
    const t = d.createElement('pre');
    t.textContent = s;
    // 表示されていないとコピー出来ないのでbodyに追加する
    d.body.appendChild(t);
    // 追加した要素を選択しコピーする
    // コピー後に追加した要素を消すので画面上はほぼ影響がない
    d.getSelection().selectAllChildren(t);
    d.execCommand('copy');
    d.body.removeChild(t);
}

document.getElementById('button').onclick = () => copyToClipboard(Date());

↓ボタンを押すと現在時刻がクリップボードにコピーされる。

See the Pen ERLxzm by baetdjam (@beatdjam) on CodePen.

【JavaScript】アロー関数

  • アロー関数のthisは定義した場所のthisで固定される
this.val = `global`;

let obj1 = {
    val: 'obj1',
    print:function(){
      console.log(this.val);
    },
    printAllow:() => {
      console.log(this.val);
    }
}

// obj1のthisを参照するので
// obj1が出力される
obj1.print();

// 定義した場所の外側のthisを参照するので
// globalが出力される
obj1.printAllow();
  • アロー関数はargumentsオブジェクトを持っていないので残余引数(rest parameters)で代用する
const restParamSample = (a,b,...r)=>{
    return console.log(a, b, r);
};
restParamSample(1,1,4,5,1,4);  //1 1  4, 5, 1, 4 

【JavaScript】スプレッド演算子

配列の展開

const value = [2, 3, 1, 4, 5];
console.log(Math.max(...value));

シャローコピー

// 配列の複製
let a = [1, 2, 3];
let b = [...a];
console.log(b); //[ 1, 2, 3 ]

// シャローコピーなので多次元配列やオブジェクト等は影響を受けてしまう
let c = [[1], [2], [3]];
let d = [...c];
c[0][0] = 0;
console.log(c); // [ [ 0 ], [ 2 ], [ 3 ] ]

配列の連結

let a = [0, 1, 2];
let b = [3, 4, 5];
let c = [...a, ...b];

console.log(c); // [ 0, 1, 2, 3, 4, 5 ]
a.push(...b);
console.log(a); // [ 0, 1, 2, 3, 4, 5 ]

配列の分割代入

let [a, ...other] = [1, 2, 3];
console.log(a, other); // 1 [ 2, 3 ]

iterableなオブジェクトを展開できる

String、NodeList、HTMLCollection等…

let sample = "sample";
console.log([...sample]); // [ 's', 'a', 'm', 'p', 'l', 'e' ]