javascript之关于函数参数的默认值的类型练习代码

一切尽在代码中


console.log(typeof c)//undefined  typeof的保护性

//弄清楚fun和foo、bar的区别
function fun({x=0,y=3}){
    console.log(x,y)
}
fun({x:1,y:2})//1 2
fun({x:1})//1 3
//fun()//会报错   !!!!!!!!!!!
//原因是fun需要一个参数{},但是你没有给(连空对象都没有给)
fun({})//0 3

console.log("=========")
function foo({x,y}={x:2,y:4}){
    console.log(x,y)
}
foo({x:4})  //4 undefined
foo()//2 4

console.log("=========")
function bar({x,y=5}={}){
    console.log(x,y)
}
bar({x:1,y:2})//1 2
bar({x:1})//1 5
bar() //不报错  比较一下与foo的区别  就是foo没有给默认参数 空对象{}
//undefined 5

//这个要看!
console.log("============")
function f(x, y = 5, z) {
    console.log([x, y, z]);
}
f() // [undefined, 5, undefined]
f(1) // [1, 5, undefined]
//f(1, ,2) // 报错 !!!!!!!!!!!!!!!!!!
f(1, undefined, 2) // [1, 5, 2]
     //设为undefined会触发默认值,null不会  !!!!
f(1,null,2)// [1,null,2]


function t(a,b=3,c){
    console.log(a+b+c)
}
console.log(t.length)//返回的是没有指定默认值的参数个数
//要注意,计算的是指定了默认值的参数之前的参数


//记得要多次对比!  这个很重点
//重点关注y中tt的变化
var tt=3
function test(y=function() {console.log("y中的第一个tt是"+tt);
    tt=4
    console.log("y中的值为"+tt)})
{
    var tt=5
    y()
    console.log("test中为"+tt)
}
test()//y中的第一个tt是3 // y中的值为4  // test中为5
console.log("全局中tt为"+tt)  //被y改变了
//全局中tt为4


console.log("====================")
function text2(y=function (){console.log("y中的tt为"+tt);tt=7})
{
    tt=10;
    y()
    console.log("现在tt值为"+tt)
}
text2()  //y中的tt为10  现在tt值为7
console.log("最后tt为"+tt) //最后tt为7

/*
var x=4;
function tem(x=x){
    //!!!!!!会出错,因为这个地方其实是let x=x   暂时性死区  x未定义
    console.log(x)
}
tem()*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值