【问题标题】:How to compress string by JS? [duplicate]JS如何压缩字符串? [复制]
【发布时间】:2020-10-03 03:20:38
【问题描述】:

尝试编写用于压缩字符串的 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);

【问题讨论】:

  • 那么您是在尝试从字符串中删除重复项,还是在执行类似Run Length Encoding 的操作?

标签: javascript


【解决方案1】:

也许对你有帮助

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))

【讨论】:

    【解决方案2】:

    您可以尝试使用 'lz-string' 在 javascript 中压缩和解压缩字符串。

    ** 我用它来压缩本地存储数据(因为本地存储只有 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>
    

    【讨论】:

      猜你喜欢
      • 2013-07-30
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      相关资源
      最近更新 更多