函数参数

    xiaoxiao2022-07-12  138

    一、对位传参

    function fn1(name,sex,age){ console.log("用户的姓名为 ",name,",性别为 ",sex,",年龄为 ",age); } fn1("tjh","男",18); --》用户的姓名为 tjh ,性别为 男 ,年龄为 18

    二、对像传参

    function fn1(porent){ console.log("用户的姓名为 ",porent.name,",性别为 ",porent.sex,",年龄为 ",porent.age); } fn1({name: "tjh",sex: "男",age: 18}); --》用户的姓名为 tjh ,性别为 男 ,年龄为 18

    三、参数默认值(三种方式)

    //ES6的写法 function fn1(porent = {name: "lj"}){ console.log("用户的姓名为 ",porent.name,",性别为 ",porent.sex,",年龄为 ",porent.age); } fn1({name: "tjh"}); --》用户的姓名为 tjh ,性别为 undefined ,年龄为 undefined //ES5的方法 function fn1(porent){ porent.name = (porent.name == undefined ? "tjh":porent.name), porent.sex = (porent.sex == undefined ? "女":porent.sex) console.log("用户的姓名为 ",porent.name,",性别为 ",porent.sex,",年龄为 ",porent.age); } fn1({name: "tjh",age: 20}); --》用户的姓名为 tjh ,性别为 女 ,年龄为 20 //ES5的方法 function fn1(porent){ porent.name = (porent.name || "wzh"), porent.sex = (porent.sex || "中") console.log("用户的姓名为 ",porent.name,",性别为 ",porent.sex,",年龄为 ",porent.age); } fn1({name: "t",age: 20}); --》用户的姓名为 t ,性别为 中 ,年龄为 20 //此方法有缺陷,当传入的值为0的时候,会传入默认值

    四、Arguments(将参数以伪数组的形式传入进行操作,有下标)

    function f1(n1,n2,n3,n4,n5){ let arr = Array.prototype.slice.call(arguments); //将伪数组转化为真数组,用call方法修改this指向,调用数组的方法 return arr.reduce(function(ele1,ele2){ return ele1 + ele2; }) } f1(1,2,3,4,5); --》15 function f1(n1,n2,n3,n4,n5){ let arr = Array.from(arguments); return arr.reduce(function(ele1,ele2){ return ele1 + ele2; }) } f1(1,2,3,4,5); --》15

     

    最新回复(0)