整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

JS中将值转换成字符串的5种方法

JS中将值转换成字符串的5种方法

果你订阅了Airbnb 的 JavaScript 风格指南,就会知道最好的方法是使用 "String()"

我用他是因为它是最明确的——容易让其他人明白你代码的意图

请记住,最好的代码并不需要多聪明的方式,而是能将你的代码理解传达给他人

const value=12345;
// Concat Empty String
value + '';
// Template Strings
`${value}`;
// JSON.stringify
JSON.stringify(value);
// toString()
value.toString();
// String()
String(value);
// RESULT
// '12345'

对比这 5 个方法

让我们用不同的值测试这 5 个方法,下面是我们打算测试的值:

const string="hello";
const number=123;
const boolean=true;
const array=[1, "2", 3];
const object={one: 1 };
const symbolValue=Symbol('123');
const undefinedValue=undefined;
const nullValue=null;

拼接空字符串

string + ''; // 'hello'
number + ''; // '123'
boolean + ''; // 'true'
array + ''; // '1,2,3'
object + ''; // '[object Object]'
undefinedValue + ''; // 'undefined'
nullValue + ''; // 'null'
symbolValue + ''; //TypeError

从这里可以看出如果值是 symbol 这个方法会抛出一个 TypeError 错误,除此之外,其他都输出正确的值

模板字符串

`${string}`; // 'hello'
`${number}`; // '123'
`${boolean}`; // 'true'
`${array}`; // '1,2,3'
`${object}`; // '[object Object]'
`${undefinedValue}`; // 'undefined'
`${nullValue}`; // 'null'
`${symbolValue}`; // ? TypeError

实际上使用模板字符串和拼接字符串是输出相同的结果,再者,当处理 Symbol 这也不是最理想的方式因为它会抛出一个 TypeError

TypeError: Cannot convert a Symbol value to a string

类型错误: 不能把 Symbol 类型的值转换为 string

JSON.stringify()

JSON.stringify(string); // '"hello"'
JSON.stringify(number); // '123'
JSON.stringify(boolean); // 'true'
JSON.stringify(array); // '[1,"2",3]'
JSON.stringify(object); // '{"one":1}'
JSON.stringify(nullValue); // 'null'
JSON.stringify(symbolValue); // undefined
JSON.stringify(undefinedValue); // undefined
复制代码

你一般也不会使用 JSON.stringify 去把一个值转成字符串,而且这里真的没有强制发生,我主要包括这种方式来完整让你了解可用的所有工具,然后你根据具体情况来挑选使用哪种方式

有个点我要指出来因为你可能没注意,当你使用一个纯字符串格式的值转换出来就会包裹引号

扩展阅读 Kyle Simpson 的 “You Don’t Know JS”: JSON Stringification

关于了解基本原理的重要性

你可能注意到我的代码笔记经常引用 Kyle 的书,我在上面学到了很多东西,我不是来自计算机科学背景,缺乏很多基本概念,他的书让我意识到明白基本原来是多么重要,对于那些想要成为高级工程师的人,真正了解基本原理是提升水平的好方法,否则很难提高。你最终知道了问题在那里,但是如果你知道了基本原理,就会知道为什么从而知道如何去解决,总之,强烈推荐这个系列给那些想成为高级程序员的人!

toString()

string.toString(); // 'hello'
number.toString(); // '123'
boolean.toString(); // 'true'
array.toString(); // '1,2,3'
object.toString(); // '[object Object]'
symbolValue.toString(); // 'Symbol(123)'
undefinedValue.toString(); // ? TypeError
nullValue.toString(); // ? TypeError

因此对比就留给了 toString 和 String, toString 也执行的不错,一定要注意的一点就是在 undefined 和 null 下面会抛出异常。

String()

String(string); // 'hello'
String(number); // '123'
String(boolean); // 'true'
String(array); // '1,2,3'
String(object); // '[object Object]'
String(symbolValue); // 'Symbol(123)'
String(undefinedValue); // 'undefined'
String(nullValue); // 'null'

最后,我们找到了冠军

可以看到 String() 处理 undefined 和 null 非常的好 ,不会抛出任何异常。记住我经常说的,你最了解你的程序,因此你应该选择最适合你的方式。

总结

在展示了所有不同的方法如何处理不同类型的值之后,希望你能意识到这些差异并且知道下次处理代码时如何使用,如果你不确认,String()是最好的选择

.NET的SelectPdf Html到Pdf转换器-社区版是.NET的SelectPdf库中提供的功能强大的html到pdf转换器的免费版本。
转换器提供了许多强大的选项(将任何网页转换为pdf,将任何html字符串转换为pdf,html5 / css3 / javascript支持,页眉和页脚支持等),唯一的限制是它最多可以生成pdf文档。5页长。
.NET的免费HTML至Pdf转换器–社区版功能:最多生成5页pdf文档,将任何网页转换为pdf,将任何原始html字符串转换为pdf,设置pdf页面设置(页面大小,页面方向,页面边距) ,在转换过程中调整内容大小以适合pdf页面,设置pdf文档属性,设置pdf查看器首选项,设置pdf安全性(密码,权限),设置转换延迟和网页导航超时,自定义页眉和页脚,在页眉中支持html和页脚,自动和手动分页符,在每个页面上重复html表头,支持@media类型屏幕和打印,支持内部和外部链接,基于html元素自动生成书签,支持HTTP标头,支持HTTP cookie,支持需要身份验证的网页,支持代理服务器,启用/禁用javascript,修改颜色空间,多线程支持,HTML5 / CSS3支持,Web字体支持等等。


代码实现

1、nuget 引用

Install-Package Select.HtmlToPdf

2、方法

  • using SelectPdf;using System.Collections.Specialized;using System.IO;using System.Web;
    namespace BQoolCommon.Helpers.File{ public class WebToPdf { public WebToPdf() { //SelectPdf.GlobalProperties.LicenseKey="your-license-key"; }
    /// <summary> /// 將 Html 轉成 PDF,並儲存成檔案 /// </summary> /// <param name="html">html</param> /// <param name="fileName">絕對路徑</param> public void SaveToFileByHtml(string html, string fileName) { var doc=SetPdfDocument(html); doc.Save(fileName); }
    /// <summary> /// 傳入 Url 轉成 PDF,並儲存成檔案 /// </summary> /// <param name="url">url</param> /// <param name="fileName">絕對路徑</param> /// <param name="httpCookies">Cookies</param> public void SaveToFileByUrl(string url, string fileName, NameValueCollection httpCookies) { var doc=SetPdfDocument(url, httpCookies); doc.Save(fileName); }
    /// <summary> /// 將 Html 轉成 PDF,並輸出成 byte[] 格式 /// </summary> /// <param name="html">html</param> /// <returns></returns> public byte[] GetFileByteByHtml(string html) { var doc=SetPdfDocument(html); return doc.Save(); }
    /// <summary> /// 傳入 Url 轉成 PDF,並輸出成 byte[] 格式 /// </summary> /// <param name="url">url</param> /// <param name="httpCookies">Cookies</param> /// <returns></returns> public byte[] GetFileByteByUrl(string url, NameValueCollection httpCookies) { var doc=SetPdfDocument(url, httpCookies); return doc.Save(); }
    /// <summary> /// 將 Html 轉成 PDF,並輸出成 Stream 格式 /// </summary> /// <param name="html">html</param> /// <returns></returns> public Stream GetFileStreamByHtml(string html) { var doc=SetPdfDocument(html); var pdfStream=new MemoryStream();
    doc.Save(pdfStream); pdfStream.Position=0;
    return pdfStream; }
    /// <summary> /// 傳入 Url 轉成 PDF,並輸出成 Stream 格式 /// </summary> /// <param name="html">html</param> /// <returns></returns> public Stream GetFileStreamByUrl(string url, NameValueCollection httpCookies) { var doc=SetPdfDocument(url, httpCookies); var pdfStream=new MemoryStream();
    doc.Save(pdfStream); pdfStream.Position=0;
    return pdfStream; }
    private PdfDocument SetPdfDocument(string html) { var converter=new HtmlToPdf();
    converter.Options.WebPageWidth=1200; html=HttpUtility.HtmlDecode(html);
    return converter.ConvertHtmlString(html); }
    private PdfDocument SetPdfDocument(string url, NameValueCollection httpCookies) { var converter=new HtmlToPdf(); converter.Options.WebPageWidth=1200;
    if (httpCookies != && httpCookies.Count !=0) { converter.Options.HttpCookies.Add(httpCookies); }
    return converter.ConvertUrl(url); }
    }}

    3、调用

    • /// <summary> /// 下载pdf /// </summary> public void Downpdf(string data) { var stream=new BQoolCommon.Helpers.File.WebToPdf().GetFileStreamByHtml(Gethtml(data)); Response.Clear(); //二进制流数据(如常见的文件下载) Response.ContentType="application/octet-stream"; //通知浏览器下载文件而不是打开 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("Profit and Loss Statement.pdf", System.Text.Encoding.UTF8)); var bytes=StreamToBytes(stream); Response.BinaryWrite(bytes); Response.Flush(); stream.Close(); stream.Dispose();
      Response.End(); }

      那么如何获取指定页面的html 呢 传入对应的model 获得指定动态的html

      • private string Gethtml(string data) { string str="";
        str=this.ControllerContext.RenderViewToString("ProfitDetails", data);
        return str; }
        • using BQoolCommon.Helpers.Format;using Newtonsoft.Json;using OrdersManager.Models.ViewModel.Report;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.Mvc;
          namespace OrdersManager.Web.Infrastructure{ public static class HelperExtensions { public static string RenderViewToString(this ControllerContext context, string viewName, string data) { if (string.IsOrEmpty(viewName)) viewName=context.RouteData.GetRequiredString("action");
          context.Controller.ViewData.Model=JsonConvert.DeserializeObject<ProfitDetailsmodel>(StringTools.Base64Decode(StringTools.Base64Decode(data)));
          using (var sw=new StringWriter()) { ViewEngineResult viewResult=ViewEngines.Engines.FindPartialView(context, viewName); var viewContext=new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw); try { viewResult.View.Render(viewContext, sw); } catch (Exception ex) { throw; }
          return sw.GetStringBuilder().ToString(); } } }}

          参考文档

          https://www.nuget.org/packages/Select.HtmlToPdf/

、nuget 引用

Select.HtmlToPdf

2、方法

  • using SelectPdf;using System.Collections.Specialized;using System.IO;using System.Web;
    namespace BQoolCommon.Helpers.File{ public class WebToPdf { public WebToPdf() { //SelectPdf.GlobalProperties.LicenseKey="your-license-key"; }
    /// <summary> /// 將 Html 轉成 PDF,並儲存成檔案 /// </summary> /// <param name="html">html</param> /// <param name="fileName">絕對路徑</param> public void SaveToFileByHtml(string html, string fileName) { var doc=SetPdfDocument(html); doc.Save(fileName); }
    /// <summary> /// 傳入 Url 轉成 PDF,並儲存成檔案 /// </summary> /// <param name="url">url</param> /// <param name="fileName">絕對路徑</param> /// <param name="httpCookies">Cookies</param> public void SaveToFileByUrl(string url, string fileName, NameValueCollection httpCookies) { var doc=SetPdfDocument(url, httpCookies); doc.Save(fileName); }
    /// <summary> /// 將 Html 轉成 PDF,並輸出成 byte[] 格式 /// </summary> /// <param name="html">html</param> /// <returns></returns> public byte[] GetFileByteByHtml(string html) { var doc=SetPdfDocument(html); return doc.Save(); }
    /// <summary> /// 傳入 Url 轉成 PDF,並輸出成 byte[] 格式 /// </summary> /// <param name="url">url</param> /// <param name="httpCookies">Cookies</param> /// <returns></returns> public byte[] GetFileByteByUrl(string url, NameValueCollection httpCookies) { var doc=SetPdfDocument(url, httpCookies); return doc.Save(); }
    /// <summary> /// 將 Html 轉成 PDF,並輸出成 Stream 格式 /// </summary> /// <param name="html">html</param> /// <returns></returns> public Stream GetFileStreamByHtml(string html) { var doc=SetPdfDocument(html); var pdfStream=new MemoryStream();
    doc.Save(pdfStream); pdfStream.Position=0;
    return pdfStream; }
    /// <summary> /// 傳入 Url 轉成 PDF,並輸出成 Stream 格式 /// </summary> /// <param name="html">html</param> /// <returns></returns> public Stream GetFileStreamByUrl(string url, NameValueCollection httpCookies) { var doc=SetPdfDocument(url, httpCookies); var pdfStream=new MemoryStream();
    doc.Save(pdfStream); pdfStream.Position=0;
    return pdfStream; }
    private PdfDocument SetPdfDocument(string html) { var converter=new HtmlToPdf();
    converter.Options.WebPageWidth=1200; html=HttpUtility.HtmlDecode(html);
    return converter.ConvertHtmlString(html); }
    private PdfDocument SetPdfDocument(string url, NameValueCollection httpCookies) { var converter=new HtmlToPdf(); converter.Options.WebPageWidth=1200;
    if (httpCookies != && httpCookies.Count !=0) { converter.Options.HttpCookies.Add(httpCookies); }
    return converter.ConvertUrl(url); }
    }}