LoginSignup
0
0

More than 1 year has passed since last update.

JavaScript すっきりリファクタリング 2

Last updated at Posted at 2022-11-24

ネット上で見かけたJavaScriptのコードをリファクタリングしていく企画です。

元コード

CSVファイルを取得して、それから<table>タグを作る。

元コード
let res = await fetch("data.csv");
let csv = await res.text();
let lines = csv.split("\n");
let table = document.createElement("table");

for (let i = 0; i < lines.length; i++) {
    let line = lines[i];
    let cells = line.split(",");
    let tr = document.createElement("tr");
    for (let j = 0; j < cells.length; j++) {
        let td = document.createElement("td");
        td.textContent = cells[j];
        tr.appendChild(td);
    }
    table.appendChild(tr);
}

新コード

新コード
const csv = await fetch("data.csv").then(res => res.text())
const table = document.createElement("table")

for(const line of csv.split("\n")){
    const tr = table.insertRow()
    for(const value of line.split(",")){
        tr.insertCell().append(value)
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0