본문으로 건너뛰기Skip to content
예제 첫화면Examples home

자바스크립트 배열 그대로 보여 주기Show a plain JavaScript array

페이지 안에 있는 배열을 서버 요청 없이 그대로 표에 넣어요. 배열을 바꾸고 다시 넘기면 표가 곧바로 따라와요.Pass an array that already lives in the page to rows, no request needed. Change the array, call setRows, and the table follows.

입문Beginner
직접 써 보기Live preview자바스크립트 배열 그대로 보여 주기Show a plain JavaScript array

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="add">메뉴 추가</button>
    <button type="button" id="removeLast">마지막 빼기</button>
    <button type="button" id="raisePrice">가격 500원 올리기</button>
    <button type="button" id="empty">빈 배열</button>
    <button type="button" id="reset">처음으로</button>
  </div>
  <div id="grid" style="height: 320px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeLast').addEventListener('click', () => actions.removeLast(api));
document.getElementById('raisePrice').addEventListener('click', () => actions.raisePrice(api));
document.getElementById('empty').addEventListener('click', () => actions.empty(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
// 페이지 안에 이미 있는 자바스크립트 배열이에요. 서버 요청 없이 그대로 rows에 넣어요.
const initial = [
  { id: 1, menu: '아메리카노', category: '커피', price: 4500, stock: 48 },
  { id: 2, menu: '카페라떼', category: '커피', price: 5000, stock: 36 },
  { id: 3, menu: '바닐라라떼', category: '커피', price: 5500, stock: 22 },
  { id: 4, menu: '유자차', category: '차', price: 5000, stock: 15 },
  { id: 5, menu: '캐모마일', category: '차', price: 4800, stock: 9 },
  { id: 6, menu: '딸기 스무디', category: '음료', price: 6500, stock: 18 },
  { id: 7, menu: '치즈 케이크', category: '디저트', price: 7000, stock: 7 },
  { id: 8, menu: '소금빵', category: '디저트', price: 3800, stock: 30 },
];
let data = [...initial];
let nextId = initial.length + 1;
let log = () => { };
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
  const ch = word.trim().slice(-1);
  const digit = '0123456789'.indexOf(ch);
  if (digit >= 0)
    return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
  const code = ch.charCodeAt(0) - 0xac00;
  return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
export const options = {
  columns: [
    { id: 'id', title: '번호', width: 70, align: 'end' },
    { id: 'menu', title: '메뉴', width: 160 },
    { id: 'category', title: '분류', width: 100 },
    {
      id: 'price',
      title: '가격',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
    },
    { id: 'stock', title: '재고', kind: 'number', width: 90, align: 'end' },
  ],
  rows: data,
  rowKey: 'id',
};
// 배열을 바꾼 뒤에는 setRows로 새 배열을 넘겨요. 기존 배열을 직접 고치지 않고 새로 만들어 주면 안전해요.
function apply(api, message) {
  api.setRows(data);
  log({
    ko: `${message.ko} (지금 ${data.length}행)`,
    en: `${message.en} (${data.length} rows now)`,
  });
}
export function setup(_api, write) {
  log = write;
  write({
    ko: `배열에 ${data.length}개의 메뉴가 들어 있어요. 버튼으로 배열을 바꿔 보세요.`,
    en: `The array holds ${data.length} menu items. Use the buttons to change it.`,
  });
}
export const actions = {
  add: (api) => {
    const row = {
      id: nextId,
      menu: `신메뉴 ${nextId}`,
      category: '디저트',
      price: 6000,
      stock: 10,
    };
    nextId += 1;
    data = [...data, row];
    apply(api, {
      ko: `배열 끝에 ${row.menu}${eulReul(row.menu)} 넣었어요`,
      en: `Added ${row.menu} to the end of the array`,
    });
  },
  removeLast: (api) => {
    const last = data[data.length - 1];
    if (!last)
      return log({ ko: '지울 행이 없어요.', en: 'No row to delete.' });
    data = data.slice(0, -1);
    apply(api, { ko: `${last.menu}${eulReul(last.menu)} 뺐어요`, en: `Removed ${last.menu}` });
  },
  raisePrice: (api) => {
    data = data.map((row) => ({ ...row, price: row.price + 500 }));
    apply(api, { ko: '모든 가격을 500원씩 올렸어요', en: 'Raised every price by 500 KRW' });
  },
  reset: (api) => {
    data = [...initial];
    nextId = initial.length + 1;
    apply(api, { ko: '처음 배열로 되돌렸어요', en: 'Back to the first array' });
  },
  empty: (api) => {
    data = [];
    apply(api, { ko: '빈 배열을 넣었어요', en: 'Set an empty array' });
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="add">Add a menu</button>
    <button type="button" id="removeLast">Remove last</button>
    <button type="button" id="raisePrice">Raise prices by $0.50</button>
    <button type="button" id="empty">Empty array</button>
    <button type="button" id="reset">Reset</button>
  </div>
  <div id="grid" style="height: 320px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('add').addEventListener('click', () => actions.add(api));
document.getElementById('removeLast').addEventListener('click', () => actions.removeLast(api));
document.getElementById('raisePrice').addEventListener('click', () => actions.raisePrice(api));
document.getElementById('empty').addEventListener('click', () => actions.empty(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
// A JavaScript array that already lives in the page. It goes straight into rows with no server request.
const initial = [
  { id: 1, menu: 'Americano', category: 'Coffee', price: 4.5, stock: 48 },
  { id: 2, menu: 'Caffe Latte', category: 'Coffee', price: 5, stock: 36 },
  { id: 3, menu: 'Vanilla Latte', category: 'Coffee', price: 5.5, stock: 22 },
  { id: 4, menu: 'Citron Tea', category: 'Tea', price: 5, stock: 15 },
  { id: 5, menu: 'Chamomile', category: 'Tea', price: 4.8, stock: 9 },
  { id: 6, menu: 'Strawberry Smoothie', category: 'Drinks', price: 6.5, stock: 18 },
  { id: 7, menu: 'Cheesecake', category: 'Dessert', price: 7, stock: 7 },
  { id: 8, menu: 'Salt Bread', category: 'Dessert', price: 3.8, stock: 30 },
];
let data = [...initial];
let nextId = initial.length + 1;
let log = () => { };
export const options = {
  columns: [
    { id: 'id', title: 'No.', width: 70, align: 'end' },
    { id: 'menu', title: 'Menu', width: 180 },
    { id: 'category', title: 'Category', width: 100 },
    {
      id: 'price',
      title: 'Price',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => `$${Number(v).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
    },
    { id: 'stock', title: 'Stock', kind: 'number', width: 90, align: 'end' },
  ],
  rows: data,
  rowKey: 'id',
};
// After changing the array, pass a new array to setRows. It is safer to build a new one than to edit the old array in place.
function apply(api, message) {
  api.setRows(data);
  log(`${message} (${data.length} rows now)`);
}
export function setup(_api, write) {
  log = write;
  write(`The array holds ${data.length} menu items. Use the buttons to change it.`);
}
export const actions = {
  add: (api) => {
    const row = {
      id: nextId,
      menu: `New item ${nextId}`,
      category: 'Dessert',
      price: 6,
      stock: 10,
    };
    nextId += 1;
    data = [...data, row];
    apply(api, `Added ${row.menu} to the end of the array`);
  },
  removeLast: (api) => {
    const last = data[data.length - 1];
    if (!last)
      return log('No row to delete.');
    data = data.slice(0, -1);
    apply(api, `Removed ${last.menu}`);
  },
  raisePrice: (api) => {
    data = data.map((row) => ({ ...row, price: Math.round((row.price + 0.5) * 10) / 10 }));
    apply(api, 'Raised every price by $0.50');
  },
  reset: (api) => {
    data = [...initial];
    nextId = initial.length + 1;
    apply(api, 'Back to the first array');
  },
  empty: (api) => {
    data = [];
    apply(api, 'Set an empty array');
  },
};