Lala Code

Lala 的前端大補帖,歡迎一起鑽研前端技術😊

0%

前端數據排序上移、下移、置頂、互換

Imgur
在前端的專案中,常常會遇到 Javascript 數據需調換順序的功能,在此做個記錄

data 為一個單純的 Array

1
2
3
4
5
6
7
const data = [
{ name: "第一個項目" },
{ name: "第二個項目" },
{ name: "第三個項目" },
{ name: "第四個項目" },
{ name: "第五個項目" },
];


上移

1
2
3
4
const clickUp = (idx) => {
if (idx === 0) return;
data[idx] = data.splice(idx - 1, 1, data[idx])[0];
};

splice 可刪除從 idx 處開始的零個或多個元素,改變原來的 data,並將被刪除的數組替換到 idx 的位置



下移

1
2
3
4
const clickDown = (idx) => {
if (idx === data.length - 1) return;
data[idx] = data.splice(idx + 1, 1, data[idx])[0];
};


置頂

1
2
3
4
const clickTop = (idx) => {
if (idx === 0) return;
data.unshift(data.splice(idx, 1)[0]);
};


互換

1
2
3
const change = (idx, idx2) => {
data[idx] = data.splice(idx2, 1, data[idx])[0];
};


Vue 範例

這邊用 Vue 來操作上移、下移、置頂、互換,附上 codesandbox

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<ul>
<li v-for="(item, idx) in data" :key="item.name">
<div>{{ idx + 1 }}. {{ item.name }}</div>
<div>
<button type="button" @click="clickUp(idx)"></button>
<button type="button" @click="clickDown(idx)"></button>
<button type="button" @click="clickTop(idx)">置頂</button>
<input type="number" v-model="item.number" @input="change(idx)" />
</div>
</li>
</ul>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script setup>
import { reactive } from "vue";
const data = reactive([
{ name: "第一個項目", number: 0 },
{ name: "第二個項目", number: 0 },
{ name: "第三個項目", number: 0 },
{ name: "第四個項目", number: 0 },
{ name: "第五個項目", number: 0 },
]);

const clickUp = (idx) => {
if (idx === 0) return;
data[idx] = data.splice(idx - 1, 1, data[idx])[0];
};

const clickDown = (idx) => {
if (idx === data.length - 1) return;
data[idx] = data.splice(idx + 1, 1, data[idx])[0];
};

const clickTop = (idx) => {
if (idx === 0) return;
data.unshift(data.splice(idx, 1)[0]);
};

const change = (idx) => {
data[idx] = data.splice(data[idx].number - 1, 1, data[idx])[0];
};
</script>



Hey!想學習更多前端知識嗎?

最近 Lala 開了前端課程 👉【實地掌握RWD - 12小時新手實戰班】👈
無論您是 0 基礎新手,又或是想學 RWD 的初學者,
我們將帶你從零開始,深入了解並掌握 RWD 響應式網頁設計的核心技術,快來一起看看吧 😊



🚀線上課程分享

線上課程可以加速學習的時間,省去了不少看文件的時間XD,以下是我推薦的一些課程
想學習更多關於前後端的線上課程,可以參考看看。

Hahow

Hahow 有各式各樣類型的課程,而且是無限次數觀看,對學生或上班族而言,不用擔心被時間綁住



六角學院

如果你是初學者,非常推薦六角學院哦!
剛開始轉職也是上了六角的課,非常的淺顯易懂,最重要的是,隨時還有線上的助教幫你解決問題!


Udemy

Udemy 裡的課程非常的多,品質普遍不錯,且價格都滿實惠的,CP值很高!
也是很多工程師推薦的線上課程網站。
❤️