最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use properties of optional object argument - Stack Overflow

programmeradmin3浏览0评论

I have this code:

function getName(type, options) {

    if (type == 'dog') {
        var name = 'Rover';
    }
    else {
        var name = options.name || 'Buddy'
    }

    return name;
}
alert(getName('cat'));

I was expecting the name variable to be assigned to 'Buddy' but instead I got this error:

Cannot read property 'name' of undefined

Is there a simple way to handle this? I'm hoping for a one-line piece of code. I was thinking about using this but it seems long and unnecessarily plex:

var name = (options !== undefined && options.name) ? options.name : 'Buddy';

I have this code:

function getName(type, options) {

    if (type == 'dog') {
        var name = 'Rover';
    }
    else {
        var name = options.name || 'Buddy'
    }

    return name;
}
alert(getName('cat'));

I was expecting the name variable to be assigned to 'Buddy' but instead I got this error:

Cannot read property 'name' of undefined

Is there a simple way to handle this? I'm hoping for a one-line piece of code. I was thinking about using this but it seems long and unnecessarily plex:

var name = (options !== undefined && options.name) ? options.name : 'Buddy';
Share Improve this question edited Sep 9, 2016 at 17:49 Cave Johnson asked Sep 9, 2016 at 17:44 Cave JohnsonCave Johnson 6,7885 gold badges41 silver badges61 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 6

You can simplify the check to options && options.name || 'Buddy' because every object is truthy.

Using optional parameters in es6 you can simply default it to an empty object so as not to deal with undefined.

function(type, options = {}) {
  return type === 'dog' ? 'Rover' : options.name || 'Buddy';
}

You can defined a default value for the property of the argument using deconstruction (see Setting a function parameter's default value). Adding = {} makes the whole argument optional, allowing for getName('cat') vs getName('cat', {}).

Note that you are not getting whole object passed as argument - just the properties you defined: getName('bat', {somekey: 'I will not be passed to the function!'}).

function getName(type, {name = 'Buddy'} = {}) {
  if (type == 'dog') {
    name = 'Rover';
  }
  return name;
}
alert(`
cat: ${getName('cat')}, 
cat with name: ${getName('cat', {name: 'Puss'})}, 
dog: ${getName('dog')}, 
dog with name: ${getName('dog', {name: 'Spot'})}`);

发布评论

评论列表(0)

  1. 暂无评论