将对象传递给 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7764536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass object to javascript function
提问by Connor Deckers
I have recently been messing around with jQuery on my website, and I have a fairly limited knowledge of Javascript. I am beginning to like the jQuery ability to pass variables to a jQuery function inside the curly braces, like so:
我最近一直在我的网站上使用 jQuery,而且我对 Javascript 的了解相当有限。我开始喜欢 jQuery 将变量传递给大括号内的 jQuery 函数的能力,如下所示:
$(somediv).animate({thisisone: 1, thisistwo: 2}, thisisavar);
What I was wondering is how I can write a Javascript function that I can pass items to inside the curly braces? I know you can write functions like this:
我想知道的是如何编写一个 Javascript 函数,我可以将项目传递到大括号内?我知道你可以写这样的函数:
function someName(var1, var2, var3...) {
}
but that doesn't support the braces? I also know that you can add no arguments and do this:
但这不支持大括号?我也知道您可以不添加任何参数并执行以下操作:
function accident() {
for( var i = 0; i < arguments.length; i++ ) {
alert("This accident was caused by " + arguments[i]);
}
}
accident("me","a car","alcohol","a tree that had no right to be in the path of my driving");
but I also want to pass outside variables instead of just a whole line of strings, if that makes sense?
但我也想传递外部变量而不是一整行字符串,如果这有意义的话?
Basically, I want a function that I can pass variables to, like so:
基本上,我想要一个可以将变量传递给的函数,如下所示:
function myFunction(neededcodehere){
//Some code here...
}
myFunction (var1, {"Option 1", "Option 2", "Option 3"}, anothervar);
回答by Felix Kling
The "braces" are making an object literal, i.e. they create an object. It is one argument.
“大括号”正在制作一个对象文字,即它们创建一个对象。这是一个论点。
Example:
例子:
function someFunc(arg) {
alert(arg.foo);
alert(arg.bar);
}
someFunc({foo: "This", bar: "works!"});
the object can be created beforehand as well:
该对象也可以预先创建:
var someObject = {
foo: "This",
bar: "works!"
};
someFunc(someObject);
I recommend to read the MDN JavaScript Guide- Working with Objects.
我建议阅读MDN JavaScript 指南-使用对象。
回答by Darin Dimitrov
function myFunction(arg) {
alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}
myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });