代码之家  ›  专栏  ›  技术社区  ›  AmerllicA

为什么atob和btoa没有不同的用途?

  •  0
  • AmerllicA  · 技术社区  · 6 年前

    我确实读过 atob() btoa() ,和 JavaScript Base64 中的解码和编码功能 MDN website 是的。

    但在使用中,我犯了个错误 但是 一切都很好,我觉得很奇怪。见以下代码:

    const en = btoa('amer');
    const de = atob(en);
    

    绝对的 console.log(de) 显示 "amer" 是的。但我犯了个错误:

    const en = atob('amer'); 
    const de = btoa(en);
    

    带着极大的惊喜, 控制台日志(de) 显示 “阿米尔” 再一次!!我不明白为什么!这个 ATOB() 方法是为了解码,我用它作为编码函数,但它起作用,然后 BTOA() 函数解码此错误的结果并返回 “阿米尔” 啊!正如我所料 de 一定是个错误和不同的东西。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Saif    6 年前

    在这些api中,出于助记的目的,“b”可以被认为代表“binary”,而“a”则代表“ascii”。但实际上,由于历史原因,这些函数的输入和输出都是Unicode字符串。

    https://www.w3.org/TR/html/webappapis.html#base64-utility-methods

    console.log(atob("testString")) // µë-JÚâ
    console.log(btoa("µë-JÚâ")) //testString==
    console.log(btoa("testString")) // dGVzdFN0cmluZw==
    console.log(atob("dGVzdFN0cmluZw==")) // testString
    console.log(atob("dGVzdFN0cmluZw")) // testString, even works with no ==