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

Javascript-将可选参数作为对象的函数?,javascript,object,parameters,optional,Javascript,Object,Parameters,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 defa

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

比如:

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"});
我在这个问题()中找到了这个解决方案,但它需要jQuery:


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

您是否正在寻找类似以下内容的功能:

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"});
查看OP的第二个答案。它提供了使用jQ的替代方案

注意:如果args通过,但计算结果为true,则Kim的代码将导致逻辑错误。 更好的解决方案:
optionalArg=(optionalArg的类型==“未定义”)?“defaultValue”:可选参数

这使参数对象成为可选对象,并使单个属性成为可选属性:

var defaults = { latitude: x, longitude: y };
function loadMap(args) {
    args = args || {};
    for (var key in defaults) {
        if (!(key in args)) {
            args[key] = default[key];
        }
    }
    ...
}

过度使用,引入全面对象克隆(ECMAScript 5.1)


这个问题肯定已经超过3年了(2018-03-02)。我搜索了这个主题,但我得到的大多数问题和排名靠前的答案似乎都过时了,如、、或

目前,支持(ECMAScript的第6版)。为了兼容性,您可以使用(或其他打包器)和(或其他编译器)编译ES6代码并将其打包到ES5。对于这个问题,ES6版本的答案可能是

那么你的问题是:

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"});

费舍尔的答案应该是公认的答案。此外,如果要重命名任何已分解的变量,同时仍保持默认值,可以这样做:

function findByCoordinates({coordinates: cords = {x: 0, y: 0}} = {}) {
  console.log(cords);
  // Some calculation...
}
使用“?”而不是“| |”,否则未定义或错误的变量中可能有错误


不要只发布链接答案。将问题标记为重复问题。-如您所见,如果您只传递一个自定义值,而将其余值留空,那么它的行为将不符合预期。而且它工作得很好。。。该代码是干净的,没有什么复杂的不同,其他10000算法有实现相同的。。。您的解决方案是迄今为止最好的!这会弄乱
loadMap({latitude:0})
Ah yea。。。我们说的0是假的。。。没关系,我们可以解决没关系。。。没有什么我不能用一些三元运算修复的!我添加了一条评论,但是我没有很好地阅读你的答案。。。这似乎也很管用,而且很甜!谢谢从您发布的MDN链接中:我想知道为什么我需要右侧的空
{}
。根据文档:
您也可以在没有右侧赋值的情况下编写函数。但是,如果省略右侧赋值,则函数在调用时将查找至少一个要提供的参数,而在其当前形式中,您只需调用drawer2015chart(),而无需提供任何参数
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);
}
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"});
function findByCoordinates({coordinates: cords = {x: 0, y: 0}} = {}) {
  console.log(cords);
  // Some calculation...
}
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"});