slice、call、join、arguments的总结

来源:互联网 发布:手机怎么找淘宝客服 编辑:程序博客网 时间:2024/06/05 04:18

javascript之slice、call、join、arguments的用法总结

1、slice字符串的截取 

2、call提取对象中的参数

3、join分隔数组对象参数 join("")默认为 “,”分隔

4、arguments对象函数,类似与数组但不是数组,不具有重载的概念,也无数据类型的概念,调用函数参数传入什么值,arguments中就存放什么.并且可以用下标的形式获取到参数的(实参)的值.可以用下标的形式获取值 arguments[0],arguments[1],arguments[2] 【下标与实参个数(arguments.length-1)相对应】 也可以给其赋值 arguments[0]=‘张三’

注:形参可以不用写,因为调用函数时实参已经存放进入arguments对象中,只需要用下标的形式获取即可

如下实例:

function test(type) {

    var result = "<" + type + "able><thead>";
    result += "<tr><th>";
    var args = Array.prototype.slice.call(arguments, 1);//从第二个参数开始截取
    result += args.join("</th><th>");//分隔对象的参数
    result += "<th></tr>";
    result += "<" + type + "body><tr><td>";
    result += args.join("</td><td>");
    result += "</td></tr>" + "</" + type + "body>";
    result += "</" + type + "able>";
    return result;

}

var listHTML = test("t", "One", "Two", "Three");
console.log(listHTML);

输出结果:

<html>
 <head></head>
 <body>
  <table>
   <thead>
    <tr>
     <th>One</th>
     <th>Two</th>
     <th>Three</th>
     <th></th>
    </tr>
   </thead>
   <tbody>
    <tr>
     <td>One</td>
     <td>Two</td>
     <td>Three</td>
    </tr>
   </tbody>
  </table>
 </body>
</html>