Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用文字符号创建JavaScript对象_Javascript_Syntax - Fatal编程技术网

使用文字符号创建JavaScript对象

使用文字符号创建JavaScript对象,javascript,syntax,Javascript,Syntax,我正在使用文字符号创建一个JavaScript对象,但我不确定如何使该对象接收如下参数: hi.say({title: "foo", body: "bar"}); 而不是hi.say(“foo”,“bar”) 当前代码: var hi = { say: function (title, body) { alert(title + "\n" + body); } }; 我之所以希望这样做,是因为我希望人们能够跳过标题,只放置正文,并对许多其他参数执行相同的操作

我正在使用文字符号创建一个JavaScript对象,但我不确定如何使该对象接收如下参数:

hi.say({title: "foo", body: "bar"});
而不是
hi.say(“foo”,“bar”)

当前代码:

var hi = {
    say: function (title, body) {
        alert(title + "\n" + body);
    }
};
我之所以希望这样做,是因为我希望人们能够跳过标题,只放置正文,并对许多其他参数执行相同的操作

这就是为什么我需要一些东西,比如如何使用jQuery函数的参数
{parameter:“yay”,parameter:“nice”}


另外,我对修改当前方法也持开放态度–请记住,会有许多参数,有些是必需的,有些是可选的,不能以特定的方式排序。

没有特殊的参数语法,只需使函数采用单个参数,这将是一个对象:

var hi = {
  say: function(obj) {
    alert(obj.title + "\n" + obj.body);
  }
}

像这样的方法应该会奏效:

var hi = {
    say: function(options) {
        if (options.title) alert(options.title + "\n" + options.body);
        else alert('you forgot the title!');
    }
}


hi.say({ //alerts title and body
    "title": "I'm a title",
    "body": "I'm the body"
});
hi.say({ //alerts you for got the title!
    "body": "I'm the body."
});
var hi = {
    say: function(options) {
        if (options.title) alert(options.title + "\n" + options.body);
        else alert('you forgot the title!');
    }
}


hi.say({ //alerts title and body
    "title": "I'm a title",
    "body": "I'm the body"
});
hi.say({ //alerts you for got the title!
    "body": "I'm the body."
});