How to have optional arguments in javascript

时间:2018-01-02 14:11:37

标签: javascript

The following function creates input fields where the user specifies type, name and a number of classes that he would like to add for the input element. Sometimes, the user is going to want to set other attributes for the element, such as step, or any other DOM attribute. That's why I want to use optional arguments:

function createInputField(type, name, classList, optional){
    var input = document.createElement('input');
    input.type = type;
    input.name = name;

    for(var i=0; i<classList.length; i++){
        input.classList.add(classList[i]);
    }

    for(key,value) in optional{ // Ugly fake code. How do I implement this in Javascript?
        input.getAttribute(key) = value;
    }    

    return input;
}

input = createInputField("number", "numberfield", ["red", "top"], {"step":"0.05"})

How do I implement this functionality in Javascript?

2 个答案:

答案 0 :(得分:1)

只需使用普通对象枚举:

for (var key in optional) {
    var value = optional[key];
    input.setAttribute(key, value);
}

这不必对参数optional本身是可选的做任何事情,以便您可以在调用中省略它。当您不想传递任何额外的dom属性时,只需提供一个空对象({})。

如果你想完全省略它(比如调用createInputField("number", "x", ["red"]),你可以将循环包裹在if (typeof optional == "object")条件中,或者使用default parameters

function createInputField(type, name, classList = [], optional = {}) {
    …
}

答案 1 :(得分:1)

这就是你需要的:

if(optional && typeof optional === 'object') {
   for(var key in optional) {
      if(input.hasOwnProperty(key)) {
         input.getAttribute(key) = optional[key];
      }
   } 
}