Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - JavaScripts参数选项(JavaScripts Parameter Options)

I just wanted to know that how can I create an object or options (whatever it is).(我只是想知道我该如何创建对象或选项(无论它是什么)。)

I have created a js file with functions named popupModal()(我已经创建了一个名为popupModal()的js文件。) for now, I'm using this function like this(目前,我正在使用此功能) popupModal(param1,param2,param3,param4,param5,param6) while calling if I don't want some parameter I have to write this.(在调用时,如果我不需要某些参数,则必须编写此代码。) popupModal(param1,undefined,param3,undefined,undefined,param6) can someone please tell me how can I modify my function so whenever I use this function I can call it like(有人可以告诉我如何修改我的功能吗,所以每当我使用此功能时,我都可以像这样) popupModal ({ param2: someValue, param6: someValue });   ask by Okasha Momin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To do what you require you need to accept a single object as an argument.(要执行您需要的操作,您需要接受一个对象作为参数。)

popupModal({ param2: 'foo', param6: 'bar' }); function popupModal(settings) { console.log(settings.param2); console.log(settings.param6); } If you wanted some parameters to be optional then you can define an object within your function which contains the default values.(如果希望某些参数是可选的,则可以在函数中定义一个包含默认值的对象。) Then you can use jQuery's $.extend() method to overwrite it with the user defined settings:(然后,您可以使用jQuery的$.extend()方法用用户定义的设置覆盖它:) popupModal({ param2: 'foo', param6: 'bar' }); function popupModal(settings) { var defaults = { param1: '1', param2: '2', param3: '3', param4: '4', param5: '5', param6: '6', } settings = $.extend(defaults, settings); console.log(settings.param1); console.log(settings.param2); console.log(settings.param3); console.log(settings.param4); console.log(settings.param5); console.log(settings.param6); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...