วิธีบีบอัดสตริงโดย JS [ซ้ำ]
Oct 03 2020
พยายามเขียน func เพื่อบีบอัดสตริง (2 ตัวอักษรเท่ากันกลายเป็น 1) อย่ารับวิธีบันทึกความคืบหน้าของการบีบอัด (ลองใช้คำสั่งผสมอื่นกับconcat- ไม่สำเร็จ) ทุกครั้งที่ฉันforใช้CodePenแบบเต็มสตริง
let pass = '1122333456';
function CompressPass(string) {
for (let i = 0; i < string.length; i++) {
let concisePassword = string.split('');
const item = string[i];
const nextItem = string[i + 1];
console.log(+item, +nextItem);
if (item === nextItem) {
concisePassword.splice(i, 1);
console.log(concisePassword);
} else {
console.log('not equal: ', +item, +nextItem);
}
};
}
CompressPass(pass);
คำตอบ
1 amirseify Oct 03 2020 at 02:20
บางทีนี่อาจช่วยคุณได้
let pass = '11223322345666600222222';
function CompressPass (string) {
string += '-';
let str = '';
for (let i = 1; i < string.length; i++) {
const nextItem = string[i];
const item = string[i - 1];
if (item != nextItem){
str += item;
}
};
return str;
}
console.log(CompressPass(pass))
1 subhadippahari Oct 03 2020 at 01:57
คุณสามารถลอง 'lz-string' เพื่อบีบอัดและคลายการบีบอัดสตริงในจาวาสคริปต์
** ฉันใช้มันเพื่อบีบอัดข้อมูลที่จัดเก็บในตัวเครื่อง (เนื่องจากที่เก็บข้อมูลในเครื่องมีขีด จำกัด เพียง 5MB)
** ผลลัพธ์อาจไม่สามารถมองเห็นได้สำหรับสตริงที่สั้นกว่า แต่คุณสามารถลองได้
ลิงค์: https://pieroxy.net/blog/pages/lz-string/index.html
ตัวอย่าง: (จากลิงค์ที่กล่าวถึงข้างต้น)
<script language="javascript" src="lz-string.js"></script>
<script>
var string = "This is my compression test.";
alert("Size of sample is: " + string.length);
var compressed = LZString.compress(string);
alert("Size of compressed sample is: " + compressed.length);
string = LZString.decompress(compressed);
alert("Sample is: " + string);
</script>