zoukankan      html  css  js  c++  java
  • 一个简单确非常实用的javascript函数

    在写js的时候,往往会碰到字符串拼接的问题,如果简单,直接使用+号连接字符串就可以了, 但是如果复杂,+用起来就非常不爽,在.net中有,Sting.Format函数,用起来还是很爽的,于是就想着js中是不是有类似的函数,答案是没有,但是js可以扩展原型,于是在网上找到很多版本的format, 功能都比较简单,也挺实用。 经过我一些思考,改造,扩展了format函数的功能, 个人感觉挺实用,代码也非常少,所以发出来共享下, 废话不多说,直接上码,代码很少,不解释。

    String.prototype.format = function() {
        
        var args, 
            ret = '',
            type = Object.prototype.toString.call(arguments[0]);
    
        if (type == "[object Object]") { 
            args = arguments;
        } else if (type == "[object Array]") {
            type = Object.prototype.toString.call(arguments[0][0]);
            if (type == "[object Object]" || type == "[object Array]") { 
                args = arguments[0];
            } else {
                args = arguments;
            }
        } else {
            args = [arguments];
        }
    
        for (var i in args) {
            var a = args[i];
            ret += this.replace(/{([w]+?)}/g, function(all, match) {
                return a[match];
            });
        }
        
        return ret;
    }
    
    1. 简单数组
        "{0}|{1}|{2}".format([2,3,4]);  // 2|3|4
        "{0}|{1}|{2}".format(["a","b","c"]);  // a|b|c
    
    1. 简单多参数
        "{0}|{1}|{2}".format(2,3,4);  // 2|3|4
        "{0}|{1}|{2}".format("a","b","c");  // a|b|c
    
    1. 数组多参数
        "{0}|{1}|{2}".format([1,2,3],[4,5,6]);  // 1|2|34|5|6
    
    1. 对象多参数
        "<li value='{v}'>{n}</li>".format({v:1,n:'n1'},{v:2,n:'n2'});  // <li value="1">n1</li><li value="2">n2</li>
    
    1. 简单对象
        "{a}|{b}|{c}".format({a:1,b:"ef",c:23});  //1|ef|23
    
    1. 数组数组
        "{0}|{1}|{2}".format([[1,2,3],[4,5,6]]);  // 1|2|34|5|6
    
    1. 对象数组
        "<li value='{v}'>{n}</li>".format([{v:1,n:'n1'},{v:2,n:'n2'}]);  // <li value="1">n1</li><li value="2">n2</li>
    
  • 相关阅读:
    C# VideoAPI
    C# 列出进程
    利用SQL为Code128码添加起始符和休止符
    SQL sysobjects 表 详解
    跳过从Win7/8升级,直接格式化全新安装 Windows 10 并自动永久激活系统的方法教程
    SQL EXCEPT INTERSECT
    C# 重启程序本身
    SQL HAVING 子句使用
    SQL over的作用及用法
    SQL 游标 Cursor 基本用法
  • 原文地址:https://www.cnblogs.com/tianqiq/p/5783239.html
Copyright © 2011-2022 走看看