Javascript-以可选参数作为对象的函数?

Jua*_*ett 3 javascript parameters object optional

我需要一个函数,它的参数是一个对象,如果我将其保留为空,它将加载默认值。

就像是:

function loadMap(args) { //args is an object and its optional

   //this is what I want to do, test args and load defauts if necesary
   /*
   pseudocode:
   if args.latitude is not set then
       give it a default value

   if args.longitude is not set then
       give it a default value

    end pseudocode */

   alert("Latitude is "+args.latitude );
   alert("Longitude is "+args.longitude );
}

//outputs the default values
loadMap();

//outputs custom values
loadMap({latitude: "x.xxxx", longitude: "-x.xxxx"});

//and should work too and output one default and one custom value
loadMap({latitude: "x.xxxx"});
Run Code Online (Sandbox Code Playgroud)

我在这个问题中找到了这个解决方案(是否有更好的方法在Javascript中执行可选函数参数?),但它需要jQuery:http : //jsfiddle.net/xy84kwdv/

这几乎是我想要的,但我不想依赖于jquery函数。

小智 9

当然,这个问题已有3年以上的历史(2018-03-02)。我搜索了这个主题,但是我得到的大多数问题和排在最前面的答案似乎都已经过时了,就像这个这个这个这个

当前,许多浏览器都支持ES6 / ECMAScript 2015ECMAScript的第六版)。为了兼容性,您可以使用WebpackJs(或另一个打包程序)和BabelJs(或另一个编译器)来编译ES6代码并将其打包到ES5。这个问题的ES6版本答案可能是Object Destructuring

function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}) {
    console.log(size, cords, radius);
    // do some chart drawing
}

drawES2015Chart({cords: {x: 18, y: 30}, radius: 30});

function fn(requiredArg, {optionalArg = 'Default Value', a = 1, b ={some: 'object'}} = {}){
    // Do with destructured values: requiredArg, optionalArg, a, and b.
    console.log(requiredArg, optionalArg, a, b);
}
Run Code Online (Sandbox Code Playgroud)

因此,对于您的问题,它将是:

function loadMap({latitude = "x.xxxx", longitude = "-x.xxxx"} = {}) {
    console.log('latitude is:', latitude, 'and longitude is:', longitude);
    console.log(`latitude is: ${latitude}, and longitude is: ${longitude}`);
}

// Call the function.
loadMap({latitude: "1.2345", longitude: "-6.7890"});
Run Code Online (Sandbox Code Playgroud)

  • 甜的!谢谢!从您发布的 MDN 链接:我想知道为什么我需要右侧的空 `{}`。根据文档:`你也可以在没有右侧赋值的情况下编写函数。但是,如果您省略右侧的赋值,则该函数将在调用时查找至少一个要提供的参数,而在其当前形式中,您可以简单地调用 drawES2015Chart() 而不提供任何参数` (4认同)

Tra*_*ace 7

您是否正在寻找类似的东西:

function loadMap(args) { 
    args = args || {}; 
    args.latitude = args.latitude || "X.XXX"; 
    args.longitude = args.longitude || "Y.YYY"; 
    alert(args.latitude);
    alert(args.longitude);
}; 

loadMap({latitude:"custom_latitude"});
Run Code Online (Sandbox Code Playgroud)