您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“如何利用JavaScript差集實(shí)現(xiàn)一個(gè)對比工具”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“如何利用JavaScript差集實(shí)現(xiàn)一個(gè)對比工具”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。
先把頁面搞一搞
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> textarea { /* border: none; */ width: 49%; height: 400px; /* font-size: 17pt; */ } #btn { width: 100%; height: 50px; position: relative; top: 0px; /* position: absolute; */ } #p2 { margin-left: 940px; margin-top: -38px; } </style> </head> <body> <button id="btn">對比</button> <textarea id="txt" type="text" placeholder="應(yīng)提交"></textarea> <textarea id="txt2" type="text" placeholder="已提交"></textarea> <hr> <p>未提交</p> <p id="p2">已提交未在人名單</p> <textarea id="txt3" type="text" placeholder="未提交"></textarea> <textarea id="txt4" type="text" placeholder="已提交未在人名單"></textarea> </body> </html>
有點(diǎn)丑,無所謂了自己用
開始寫JS代碼
<script //先把輸入框,按鈕獲取一下 let txt = document.querySelector("#txt") let txt2 = document.querySelector("#txt2") let txt3 = document.querySelector("#txt3") let txt4 = document.querySelector("#txt4") let btn = document.querySelector("#btn") //然后寫一個(gè)數(shù)組去重求差集 const getDifference = function (a, b) { //解釋:如果傳入的兩個(gè)函數(shù)是數(shù)組 if (a.constructor === Array && b.constructor === Array) { let set1 = new Set(a); let set2 = new Set(b); // 利用Set去重,篩選找到差值 return Array.from(new Set([...set1].filter(x => !set2.has(x)))); } return null; } //簡簡單單給按鈕來一個(gè)點(diǎn)擊事件吧 btn.onclick = function () { //應(yīng)提交人名單 let Should_sub = txt.value.split(" ") //未提交人名單 let already_sub = txt2.value.split(" ") let l3 = getDifference(Should_sub, already_sub) //未在人名單中提交人數(shù) let l4 = getDifference(already_sub, Should_sub) //篩選好的值反饋給頁面的兩個(gè)輸入框 txt3.value = l3.join(" ") txt4.value = l4.join(" ") } </script>
讀到這里,這篇“如何利用JavaScript差集實(shí)現(xiàn)一個(gè)對比工具”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。