how to add a default value to a javascript function variable?

Possible Duplicate:
Is there a better way to do optional function parameters in Javascript?
Default value for function parameter?

I can I do this on javascript (jQuery) function

function somename(variableone = "content"){
 return variableone;
}

Now to access that function:

alert(somename()) //this should alert "content"
alert(somename("hello world"); //this should return "hello world"

but I get this error Uncaught SyntaxError: Unexpected token =

If this is not possible, is there a way to achieve the same result? OR most importantly is this a good (correct) practice.


function somename(variableone){
    if(typeof variableone === "undefined")
        variableone = "content"
    return variableone;
}

function somename(variableone) {
    variableone = arguments.length < 1 ? "content" : variableone;
    return variableone;
}

你需要使用一个条件:

function somename(variableone){
    if (typeof(variableone) === "undefined") {
        variableone = "content";
    }
    return variableone;
}
链接地址: http://www.djcxy.com/p/17278.html

上一篇: javascript:在函数中定义一个变量

下一篇: 如何将默认值添加到JavaScript函数变量?