javascript函数参数问题
PHP中文网
PHP中文网 2017-04-10 15:37:05
[JavaScript讨论组]
function testabc(a, b, c) {
    a = typeof a !== 'undefined' ? a : '1';
    b = typeof b !== 'undefined' ? b : '2';
    c = typeof c !== 'undefined' ? c : '3';

    alert(b);
}

testabc(b='b');

JS不能这么用吗?类似$.ajax这种用法是如何实现的呢?

$.ajax({
    url: 'xxx'
});
PHP中文网
PHP中文网

认证0级讲师

全部回复(4)
高洛峰

第一个,JavaScript是不能这么用的。你可以这样:

jstestabc(null, 'b');

对于$.ajax(),它是jQuery提供的一个方法,$指jQuery,而ajax是它提供的一个方法,这相当于往ajax()方法传了个参数。

如果你想要和$.ajax()这样传参数,你需要这样做:

jsfunction testabc(arg) {
    var a = typeof arg['a'] !== 'undefined' ? arg['a'] : '1';
    var b = typeof arg['b'] !== 'undefined' ? arg['b'] : '2';
    var c = typeof arg['c'] !== 'undefined' ? arg['c'] : '3';

    console.log(b);
}

testabc({b: 'b'});
ringa_lee

JS不能这么用吗?

  • 不能

类似$.ajax这种用法是如何实现的呢?

  • $.ajax的参数是一个object对象,注意括号里面的大括号。
ringa_lee

JS函数的参数其实是在一个argument变量里面,所以其实函数是这样的

function testabc(){
    var a = arguments[0],
        b = arguments[1],
        c = arguments[2];

    a = typeof a !== 'undefined' ? a : '1';
    b = typeof b !== 'undefined' ? b : '2';
    c = typeof c !== 'undefined' ? c : '3';

    alert(b);
}
testabc(undefined, b='b', undefined); //你需要手动的占位arguments的坐标,才能对应到相应的变量。
PHP中文网

b="b" 返回 “b” 且会创建一个全局变量b ,你这样相当于 b= ‘b’ ;testabc('b'); 你的具体需求没说明白。。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号