最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用js實(shí)現(xiàn)數(shù)據(jù)格式化

 更新時(shí)間:2014年12月03日 10:13:19   投稿:hebedich  
這篇文章主要介紹了使用javascript實(shí)現(xiàn)數(shù)據(jù)格式化為字符串,非常的實(shí)用,這里推薦給有相同需求的小伙伴。

格式化是通過格式操作使任意類型的數(shù)據(jù)轉(zhuǎn)換成一個(gè)字符串。例如下面這樣

復(fù)制代碼 代碼如下:

<script>
console.log(chopper.format('{0} - {1} - {2}', 12, 24, 25)); // outputs "12 - 24 - 25"
</script>

下面是一個(gè)完整的代碼,可以復(fù)制到自己的項(xiàng)目中。

復(fù)制代碼 代碼如下:

 <!DOCTYPE html>
 <html>
     <head>
         <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
     </head>
     <body>
         <script src=">
         <script>
         (function() {
             var chopper = window.chopper = window.chopper || { cultures: {} },
                 math = Math,
                 formatRegExp = /\{(\d+)(:[^\}]+)?\}/g,
                 FUNCTION = "function",
                 STRING = "string",
                 NUMBER = "number",
                 OBJECT = "object",
                 NULL = "null",
                 BOOLEAN = "boolean",
                 UNDEFINED = "undefined",
                 slice = [].slice,
                 globalize = window.Globalize,
                 standardFormatRegExp =  /^(n|c|p|e)(\d*)$/i,
                 literalRegExp = /(
\\.)|(['][^']*[']?)|(["][^"]*["]?)/g,
                 commaRegExp = /\,/g,
                 EMPTY = "",
                 POINT = ".",
                 COMMA = ",",
                 SHARP = "#",
                 ZERO = "0",
                 PLACEHOLDER = "??",
                 EN = "en-US",
                 objectToString = {}.toString;
             //cultures
             chopper.cultures["en-US"] = {
                 name: EN,
                 numberFormat: {
                     pattern: ["-n"],
                     decimals: 2,
                     ",": ",",
                     ".": ".",
                     groupSize: [3],
                     percent: {
                         pattern: ["-n %", "n %"],
                         decimals: 2,
                         ",": ",",
                         ".": ".",
                         groupSize: [3],
                         symbol: "%"
                     },
                     currency: {
                         pattern: ["($n)", "$n"],
                         decimals: 2,
                         ",": ",",
                         ".": ".",
                         groupSize: [3],
                         symbol: "$"
                     }
                 },
                 calendars: {
                     standard: {
                         days: {
                             names: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
                             namesAbbr: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
                             namesShort: [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ]
                         },
                         months: {
                             names: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                             namesAbbr: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
                         },
                         AM: [ "AM", "am", "AM" ],
                         PM: [ "PM", "pm", "PM" ],
                         patterns: {
                             d: "M/d/yyyy",
                             D: "dddd, MMMM dd, yyyy",
                             F: "dddd, MMMM dd, yyyy h:mm:ss tt",
                             g: "M/d/yyyy h:mm tt",
                             G: "M/d/yyyy h:mm:ss tt",
                             m: "MMMM dd",
                             M: "MMMM dd",
                             s: "yyyy'-'MM'-'ddTHH':'mm':'ss",
                             t: "h:mm tt",
                             T: "h:mm:ss tt",
                             u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
                             y: "MMMM, yyyy",
                             Y: "MMMM, yyyy"
                         },
                         "/": "/",
                         ":": ":",
                         firstDay: 0,
                         twoDigitYearMax: 2029
                     }
                 }
             };
              function findCulture(culture) {
                 if (culture) {
                     if (culture.numberFormat) {
                         return culture;
                     }
                     if (typeof culture === STRING) {
                         var cultures = chopper.cultures;
                         return cultures[culture] || cultures[culture.split("-")[0]] || null;
                     }
                     return null;
                 }
                 return null;
             }
             function getCulture(culture) {
                 if (culture) {
                     culture = findCulture(culture);
                 }
                 return culture || chopper.cultures.current;
             }
             function expandNumberFormat(numberFormat) {
                 numberFormat.groupSizes = numberFormat.groupSize;
                 numberFormat.percent.groupSizes = numberFormat.percent.groupSize;
                 numberFormat.currency.groupSizes = numberFormat.currency.groupSize;
             }
             chopper.culture = function(cultureName) {
                 var cultures = chopper.cultures, culture;
                 if (cultureName !== undefined) {
                     culture = findCulture(cultureName) || cultures[EN];
                     culture.calendar = culture.calendars.standard;
                     cultures.current = culture;
                     if (globalize && !globalize.load) {
                         expandNumberFormat(culture.numberFormat);
                     }
                 } else {
                     return cultures.current;
                 }
             };
             chopper.culture(EN);
             //number formatting
             function formatNumber(number, format, culture) {
                 culture = getCulture(culture);
                 var numberFormat = culture.numberFormat,
                     groupSize = numberFormat.groupSize[0],
                     groupSeparator = numberFormat[COMMA],
                     decimal = numberFormat[POINT],
                     precision = numberFormat.decimals,
                     pattern = numberFormat.pattern[0],
                     literals = [],
                     symbol,
                     isCurrency, isPercent,
                     customPrecision,
                     formatAndPrecision,
                     negative = number < 0,
                     integer,
                     fraction,
                     integerLength,
                     fractionLength,
                     replacement = EMPTY,
                     value = EMPTY,
                     idx,
                     length,
                     ch,
                     hasGroup,
                     hasNegativeFormat,
                     decimalIndex,
                     sharpIndex,
                     zeroIndex,
                     hasZero, hasSharp,
                     percentIndex,
                     currencyIndex,
                     startZeroIndex,
                     start = -1,
                     end;
                 //return empty string if no number
                 if (number === undefined) {
                     return EMPTY;
                 }
                 if (!isFinite(number)) {
                     return number;
                 }
                 //if no format then return number.toString() or number.toLocaleString() if culture.name is not defined
                 if (!format) {
                     return culture.name.length ? number.toLocaleString() : number.toString();
                 }
                 formatAndPrecision = standardFormatRegExp.exec(format);
                 // standard formatting
                 if (formatAndPrecision) {
                     format = formatAndPrecision[1].toLowerCase();
                     isCurrency = format === "c";
                     isPercent = format === "p";
                     if (isCurrency || isPercent) {
                         //get specific number format information if format is currency or percent
                         numberFormat = isCurrency ? numberFormat.currency : numberFormat.percent;
                         groupSize = numberFormat.groupSize[0];
                         groupSeparator = numberFormat[COMMA];
                         decimal = numberFormat[POINT];
                         precision = numberFormat.decimals;
                         symbol = numberFormat.symbol;
                         pattern = numberFormat.pattern[negative ? 0 : 1];
                     }
                     customPrecision = formatAndPrecision[2];
                     if (customPrecision) {
                         precision = +customPrecision;
                     }
                     //return number in exponential format
                     if (format === "e") {
                         return customPrecision ? number.toExponential(precision) : number.toExponential(); // toExponential() and toExponential(undefined) differ in FF #653438.
                     }
                     // multiply if format is percent
                     if (isPercent) {
                         number *= 100;
                     }
                     number = round(number, precision);
                     negative = number < 0;
                     number = number.split(POINT);
                     integer = number[0];
                     fraction = number[1];
                     //exclude "-" if number is negative.
                     if (negative) {
                         integer = integer.substring(1);
                     }
                     value = integer;
                     integerLength = integer.length;
                     //add group separator to the number if it is longer enough
                     if (integerLength >= groupSize) {
                         value = EMPTY;
                         for (idx = 0; idx < integerLength; idx++) {
                             if (idx > 0 && (integerLength - idx) % groupSize === 0) {
                                 value += groupSeparator;
                             }
                             value += integer.charAt(idx);
                         }
                     }
                     if (fraction) {
                         value += decimal + fraction;
                     }
                     if (format === "n" && !negative) {
                         return value;
                     }
                     number = EMPTY;
                     for (idx = 0, length = pattern.length; idx < length; idx++) {
                         ch = pattern.charAt(idx);
                         if (ch === "n") {
                             number += value;
                         } else if (ch === "$" || ch === "%") {
                             number += symbol;
                         } else {
                             number += ch;
                         }
                     }
                     return number;
                 }
                 //custom formatting
                 //
                 //separate format by sections.
                 //make number positive
                 if (negative) {
                     number = -number;
                 }
                 if (format.indexOf("'") > -1 || format.indexOf("\"") > -1 || format.indexOf("\\") > -1) {
                     format = format.replace(literalRegExp, function (match) {
                         var quoteChar = match.charAt(0).replace("\\", ""),
                             literal = match.slice(1).replace(quoteChar, "");
                         literals.push(literal);
                         return PLACEHOLDER;
                     });
                 }
                 format = format.split(";");
                 if (negative && format[1]) {
                     //get negative format
                     format = format[1];
                     hasNegativeFormat = true;
                 } else if (number === 0) {
                     //format for zeros
                     format = format[2] || format[0];
                     if (format.indexOf(SHARP) == -1 && format.indexOf(ZERO) == -1) {
                         //return format if it is string constant.
                         return format;
                     }
                 } else {
                     format = format[0];
                 }
                 percentIndex = format.indexOf("%");
                 currencyIndex = format.indexOf("$");
                 isPercent = percentIndex != -1;
                 isCurrency = currencyIndex != -1;
                 //multiply number if the format has percent
                 if (isPercent) {
                     number *= 100;
                 }
                 if (isCurrency && format[currencyIndex - 1] === "\\") {
                     format = format.split("\\").join("");
                     isCurrency = false;
                 }
                 if (isCurrency || isPercent) {
                     //get specific number format information if format is currency or percent
                     numberFormat = isCurrency ? numberFormat.currency : numberFormat.percent;
                     groupSize = numberFormat.groupSize[0];
                     groupSeparator = numberFormat[COMMA];
                     decimal = numberFormat[POINT];
                     precision = numberFormat.decimals;
                     symbol = numberFormat.symbol;
                 }
                 hasGroup = format.indexOf(COMMA) > -1;
                 if (hasGroup) {
                     format = format.replace(commaRegExp, EMPTY);
                 }
                 decimalIndex = format.indexOf(POINT);
                 length = format.length;
                 if (decimalIndex != -1) {
                     fraction = number.toString().split("e");
                     if (fraction[1]) {
                         fraction = round(number, Math.abs(fraction[1]));
                     } else {
                         fraction = fraction[0];
                     }
                     fraction = fraction.split(POINT)[1] || EMPTY;
                     zeroIndex = format.lastIndexOf(ZERO) - decimalIndex;
                     sharpIndex = format.lastIndexOf(SHARP) - decimalIndex;
                     hasZero = zeroIndex > -1;
                     hasSharp = sharpIndex > -1;
                     idx = fraction.length;
                     if (!hasZero && !hasSharp) {
                         format = format.substring(0, decimalIndex) + format.substring(decimalIndex + 1);
                         length = format.length;
                         decimalIndex = -1;
                         idx = 0;
                     } if (hasZero && zeroIndex > sharpIndex) {
                         idx = zeroIndex;
                     } else if (sharpIndex > zeroIndex) {
                         if (hasSharp && idx > sharpIndex) {
                             idx = sharpIndex;
                         } else if (hasZero && idx < zeroIndex) {
                             idx = zeroIndex;
                         }
                     }
                     if (idx > -1) {
                         number = round(number, idx);
                     }
                 } else {
                     number = round(number);
                 }
                 sharpIndex = format.indexOf(SHARP);
                 startZeroIndex = zeroIndex = format.indexOf(ZERO);
                 //define the index of the first digit placeholder
                 if (sharpIndex == -1 && zeroIndex != -1) {
                     start = zeroIndex;
                 } else if (sharpIndex != -1 && zeroIndex == -1) {
                     start = sharpIndex;
                 } else {
                     start = sharpIndex > zeroIndex ? zeroIndex : sharpIndex;
                 }
                 sharpIndex = format.lastIndexOf(SHARP);
                 zeroIndex = format.lastIndexOf(ZERO);
                 //define the index of the last digit placeholder
                 if (sharpIndex == -1 && zeroIndex != -1) {
                     end = zeroIndex;
                 } else if (sharpIndex != -1 && zeroIndex == -1) {
                     end = sharpIndex;
                 } else {
                     end = sharpIndex > zeroIndex ? sharpIndex : zeroIndex;
                 }
                 if (start == length) {
                     end = start;
                 }
                 if (start != -1) {
                     value = number.toString().split(POINT);
                     integer = value[0];
                     fraction = value[1] || EMPTY;
                     integerLength = integer.length;
                     fractionLength = fraction.length;
                     if (negative && (number * -1) >= 0) {
                         negative = false;
                     }
                     //add group separator to the number if it is longer enough
                     if (hasGroup) {
                         if (integerLength === groupSize && integerLength < decimalIndex - startZeroIndex) {
                             integer = groupSeparator + integer;
                         } else if (integerLength > groupSize) {
                             value = EMPTY;
                             for (idx = 0; idx < integerLength; idx++) {
                                 if (idx > 0 && (integerLength - idx) % groupSize === 0) {
                                     value += groupSeparator;
                                 }
                                 value += integer.charAt(idx);
                             }
                             integer = value;
                         }
                     }
                     number = format.substring(0, start);
                     if (negative && !hasNegativeFormat) {
                         number += "-";
                     }
                     for (idx = start; idx < length; idx++) {
                         ch = format.charAt(idx);
                         if (decimalIndex == -1) {
                             if (end - idx < integerLength) {
                                 number += integer;
                                 break;
                             }
                         } else {
                             if (zeroIndex != -1 && zeroIndex < idx) {
                                 replacement = EMPTY;
                             }
                             if ((decimalIndex - idx) <= integerLength && decimalIndex - idx > -1) {
                                 number += integer;
                                 idx = decimalIndex;
                             }
                             if (decimalIndex === idx) {
                                 number += (fraction ? decimal : EMPTY) + fraction;
                                 idx += end - decimalIndex + 1;
                                 continue;
                             }
                         }
                         if (ch === ZERO) {
                             number += ch;
                             replacement = ch;
                         } else if (ch === SHARP) {
                             number += replacement;
                         }
                     }
                     if (end >= start) {
                         number += format.substring(end + 1);
                     }
                     //replace symbol placeholders
                     if (isCurrency || isPercent) {
                         value = EMPTY;
                         for (idx = 0, length = number.length; idx < length; idx++) {
                             ch = number.charAt(idx);
                             value += (ch === "$" || ch === "%") ? symbol : ch;
                         }
                         number = value;
                     }
                     length = literals.length;
                     if (length) {
                         for (idx = 0; idx < length; idx++) {
                             number = number.replace(PLACEHOLDER, literals[idx]);
                         }
                     }
                 }
                 return number;
             }
             var round = function(value, precision) {
                 precision = precision || 0;
                 value = value.toString().split('e');
                 value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + precision) : precision)));
                 value = value.toString().split('e');
                 value = +(value[0] + 'e' + (value[1] ? (+value[1] - precision) : -precision));
                 return value.toFixed(precision);
             };
             var toString = function(value, fmt, culture) {
                 if (fmt) {
                     if (typeof value === NUMBER) {
                         return formatNumber(value, fmt, culture);
                     }
                 }
                 return value !== undefined ? value : "";
             };
             if (globalize && !globalize.load) {
                 toString = function(value, format, culture) {
                     if ($.isPlainObject(culture)) {
                         culture = culture.name;
                     }
                     return globalize.format(value, format, culture);
                 };
             }
             chopper.format = function(fmt) {
                 var values = arguments;
                 return fmt.replace(formatRegExp, function(match, index, placeholderFormat) {
                     var value = values[parseInt(index, 10) + 1];
                     return toString(value, placeholderFormat ? placeholderFormat.substring(1) : "");
                 });
             };
         })();
         </script>
     </body>
 </html>

API:

復(fù)制代碼 代碼如下:

chopper.format('{0} is playing {1}', 'Xiaoming', 'basketball'); // outputs "Xiaoming is playing basketball"
// 價(jià)格
chopper.format('{0:c} - {1:c}', 10, 20); // outputs "10.00−20.00"
// 指數(shù)
chopper.format('指數(shù): {0:e}', 25); // outputs "指數(shù): 2.5e+1"
// 百分?jǐn)?shù)
chopper.format('百分?jǐn)?shù): {0:p}', 25); // outputs "百分?jǐn)?shù): 2,500.00 %"
// 小數(shù)
chopper.format('小數(shù): {0:n}', 25); // outputs "小數(shù): 25.00"

小結(jié):

開發(fā)中格式化數(shù)據(jù)還是經(jīng)常用到的,比如我們要根據(jù)變量提示不同的信息,但是內(nèi)容模板都是一樣的,這樣的話我們就可以使用此方法。如果你的項(xiàng)目使用jQuery,你也可以將上面的javascript封裝成jQuery插件。

相關(guān)文章

  • Nginx上傳文件全部緩存解決方案

    Nginx上傳文件全部緩存解決方案

    Nginx默認(rèn)會(huì)對(duì)上傳的文件先在本地進(jìn)行緩存,再轉(zhuǎn)發(fā)到應(yīng)用服務(wù)器。請(qǐng)問怎么禁止掉這個(gè)緩存,讓Nginx只轉(zhuǎn)發(fā)而不緩存文件?本文給大家詳細(xì)介紹Nginx上傳文件全部緩存解決方案,有需要的朋友來參考下
    2015-08-08
  • js關(guān)于命名空間的函數(shù)實(shí)例

    js關(guān)于命名空間的函數(shù)實(shí)例

    這篇文章主要介紹了js關(guān)于命名空間的函數(shù),實(shí)例講述了namespace函數(shù)的使用技巧,需要的朋友可以參考下
    2015-02-02
  • javascript 二分法(數(shù)組array)

    javascript 二分法(數(shù)組array)

    擴(kuò)展Array對(duì)象,為其添加二分法查找功能,提高查找效率。
    2010-04-04
  • 一篇文章帶你詳細(xì)了解JavaScript數(shù)組

    一篇文章帶你詳細(xì)了解JavaScript數(shù)組

    本文是小編給大家特意整理的關(guān)于JavaScript數(shù)組的知識(shí),非常實(shí)用,在面試筆試題中經(jīng)常用得到,有需要的朋友可以參考下
    2021-09-09
  • JavaScript原型鏈與繼承操作實(shí)例總結(jié)

    JavaScript原型鏈與繼承操作實(shí)例總結(jié)

    這篇文章主要介紹了JavaScript原型鏈與繼承操作,結(jié)合實(shí)例形式總結(jié)分析了javascript原形鏈與繼承的相關(guān)概念、使用方法及操作注意事項(xiàng),需要的朋友可以參考下
    2018-08-08
  • js實(shí)現(xiàn)簡(jiǎn)單的二級(jí)聯(lián)動(dòng)效果

    js實(shí)現(xiàn)簡(jiǎn)單的二級(jí)聯(lián)動(dòng)效果

    本文主要介紹了js實(shí)現(xiàn)簡(jiǎn)單的二級(jí)聯(lián)動(dòng)效果的實(shí)例,具有很好的參考價(jià)值。下面跟著小編一起來看下吧
    2017-03-03
  • JavaScript設(shè)置獲取和設(shè)置屬性的方法

    JavaScript設(shè)置獲取和設(shè)置屬性的方法

    這篇文章主要介紹了JavaScript設(shè)置獲取和設(shè)置屬性的方法,學(xué)會(huì)使用getAttribute、setAttribute的用法,需要的朋友可以參考下
    2015-03-03
  • 在weex中愉快的使用scss的方法步驟

    在weex中愉快的使用scss的方法步驟

    這篇文章主要介紹了在weex中愉快的使用scss的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-01-01
  • ie8 不支持new Date(2012-11-10)問題的解決方法

    ie8 不支持new Date(2012-11-10)問題的解決方法

    使用JS的時(shí)候也碰到了如下問題,后來經(jīng)過修改,在IE8環(huán)境里,下面的代碼是可用的,下面與大家分享下ie8 不支持new Date的解決方法,有類似問題的朋友可以參考下
    2013-07-07
  • js獲取指定日期周數(shù)以及星期幾的小例子

    js獲取指定日期周數(shù)以及星期幾的小例子

    根據(jù)某年某周獲取一周的日期。如開始日期規(guī)定為星期四到下一周的星期五為一周,需要的朋友可以參考下
    2014-06-06

最新評(píng)論

崇礼县| 博客| 乌审旗| 贵溪市| 聂荣县| 广西| 荔浦县| 碌曲县| 连平县| 稻城县| 彝良县| 古浪县| 屯门区| 阿克陶县| 汶上县| 新宾| 嘉黎县| 台江县| 清原| 六安市| 页游| 宣武区| 元江| 德州市| 龙里县| 姜堰市| 北碚区| 两当县| 广饶县| 祥云县| 咸阳市| 孙吴县| 德惠市| 常德市| 中江县| 泰州市| 仙游县| 康保县| 河西区| 临汾市| 乐业县|