Javascript - 以可选参数作为对象的函数?
Javascript - function with optional parameters as object?
我需要一个函数,它的参数是一个对象,如果我把它留空它会加载默认值。
类似于:
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"});
我在这个问题 (Is there a better way to do optional function parameters in Javascript?) 中找到了这个解决方案,但它需要 jQuery:
http://jsfiddle.net/xy84kwdv/
这几乎是我想要的,但我不想依赖 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"});
How to overload functions in javascript?
查看OP的第二个答案。它提供了使用 jQ 的替代方法。
注意:如果 args 通过但计算结果为真,Kim 的代码将导致逻辑错误。
更好的解决方法:
optionalArg = (typeof optionalArg === "undefined") ? "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)
function cloneOwnProperties(A, B, overwrite) { // this is shallow
var i, p;
if (!(A instanceof Object)) {
if (undefined === A) A = {};
else throw new TypeError('cloneOwnProperties called on non-object');
}
if (!B) B = {};
p = Object.getOwnPropertyNames(A);
for (i = 0; i < p.length; ++i)
if (overwrite || !(p[i] in B))
Object.defineProperty(B, p[i], Object.getOwnPropertyDescriptor(A, p[i]));
return B;
}
// and for completeness
function cloneObject(obj_in, clone_seal, clone_frozen) {
var obj_out;
if (!(obj_in instanceof Object))
throw new TypeError('cloneObject called on non-object');
obj_out = Object.create(Object.getPrototypeOf(obj_in));
cloneOwnProperties(obj_in, obj_out, true);
if (clone_seal && Object.isSealed(obj_in)) Object.seal(obj_out);
if (clone_frozen && Object.isFrozen(obj_in)) Object.freeze(obj_out);
return obj_out;
}
// back on topic
现在您可以使用它来设置一些默认值
function foo(bar) {
bar = cloneOwnProperties(bar, {
fizz: true,
buzz: false
}, true);
return bar;
}
foo({buzz: 'user_value'}); // {fizz: true, buzz: "user_value"}
这个问题肯定已经超过 3 年了(2018-03-02)。我搜索了这个主题,但我得到的大部分问题和排名靠前的答案似乎已经过时,例如 this, this, this, or .
目前,lots of browsers support ES6/ECMAScript 2015(the 6th Edition of ECMAScript). For compatibility, you can use WebpackJs(or another packer) and BabelJs(or another compiler) to compile and pack your ES6 codes to ES5. And the ES6-version answer for this question may be 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);
}
所以对于你的问题,它将是:
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"});
Fisher 的答案应该是公认的答案。另外,如果你想重命名任何解构的变量,同时仍然保持默认值,你可以这样做:
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"});
我需要一个函数,它的参数是一个对象,如果我把它留空它会加载默认值。
类似于:
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"});
我在这个问题 (Is there a better way to do optional function parameters in Javascript?) 中找到了这个解决方案,但它需要 jQuery: http://jsfiddle.net/xy84kwdv/
这几乎是我想要的,但我不想依赖 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"});
How to overload functions in javascript? 查看OP的第二个答案。它提供了使用 jQ 的替代方法。
注意:如果 args 通过但计算结果为真,Kim 的代码将导致逻辑错误。 更好的解决方法: optionalArg = (typeof optionalArg === "undefined") ? "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)
function cloneOwnProperties(A, B, overwrite) { // this is shallow
var i, p;
if (!(A instanceof Object)) {
if (undefined === A) A = {};
else throw new TypeError('cloneOwnProperties called on non-object');
}
if (!B) B = {};
p = Object.getOwnPropertyNames(A);
for (i = 0; i < p.length; ++i)
if (overwrite || !(p[i] in B))
Object.defineProperty(B, p[i], Object.getOwnPropertyDescriptor(A, p[i]));
return B;
}
// and for completeness
function cloneObject(obj_in, clone_seal, clone_frozen) {
var obj_out;
if (!(obj_in instanceof Object))
throw new TypeError('cloneObject called on non-object');
obj_out = Object.create(Object.getPrototypeOf(obj_in));
cloneOwnProperties(obj_in, obj_out, true);
if (clone_seal && Object.isSealed(obj_in)) Object.seal(obj_out);
if (clone_frozen && Object.isFrozen(obj_in)) Object.freeze(obj_out);
return obj_out;
}
// back on topic
现在您可以使用它来设置一些默认值
function foo(bar) {
bar = cloneOwnProperties(bar, {
fizz: true,
buzz: false
}, true);
return bar;
}
foo({buzz: 'user_value'}); // {fizz: true, buzz: "user_value"}
这个问题肯定已经超过 3 年了(2018-03-02)。我搜索了这个主题,但我得到的大部分问题和排名靠前的答案似乎已经过时,例如 this, this, this, or
目前,lots of browsers support ES6/ECMAScript 2015(the 6th Edition of ECMAScript). For compatibility, you can use WebpackJs(or another packer) and BabelJs(or another compiler) to compile and pack your ES6 codes to ES5. And the ES6-version answer for this question may be 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);
}
所以对于你的问题,它将是:
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"});
Fisher 的答案应该是公认的答案。另外,如果你想重命名任何解构的变量,同时仍然保持默认值,你可以这样做:
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"});