【JS】利用函数里才有的arguments对象和正则表达式来模拟C语言中的printf

说明:

arguments对象是JS函数里才有的对象,它是个指向输入参数的数组,通过下标我们就能访问每个参数;

而将{n} 替换成arguments[n+1]是通过JS的正则表达式替换做到的。

有了这两项,printf的核心技术就展现无遗了。

代码:

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>标题</title>
     <style type="text/css">
     /*CSS样式*/

     </style>
    </head>

     <body>
        内容
     </body>
</html>
<script type="text/javascript">
<!--
    function printf(format){
        for(var i=1;i<arguments.length;i++){
            var re=new RegExp('[{]'+(i-1)+'[}]','g');
            format=format.replace(re,arguments[i]);
        }

        console.log(format);
    }

    printf("{0} {1}",'Hello','World');
    printf("There are {0} rabbits under the {1}",2,'tree');
    printf("{0},{1} and {2} are all {3}",'Apple','Orange','Banana','fruit');
//-->
</script>

以上粗体部分为核心函数。

输出:

Hello World
Noname2.html:24 There are 2 rabbits under the tree
Noname2.html:24 Apple,Orange and Banana are all fruit

END

原文地址:https://www.cnblogs.com/heyang78/p/15643017.html