简体   繁体   English

处理在JavaScript中作为参数传递的空对象

[英]handle empty object passed as argument in javascript

Good day all. 大家好。

I have this problem: I must provide a way to pass some optional arguments to a javascript function, this is pretty easy, ok. 我有这个问题:我必须提供一种将一些可选参数传递给javascript函数的方法,这很容易,可以。 I decide to make all the arguments be an object, so anyone who need to call the function must provide the name of the arguments. 我决定使所有参数成为一个对象,因此任何需要调用该函数的人都必须提供参数的名称。 But most of the time, the editors simply call the functions with the whole argument object, without omitting the empty arguments, because arguments are passed to the page via another way (let's say in the querystring, but it doesen't matter). 但是大多数时候,编辑器只是使用整个参数对象调用函数,而不会忽略空参数,因为参数是通过另一种方式传递到页面的(比如在querystring中说,但这没关系)。

here it is how I have made the function: 这是我制作函数的方式:

function playAnimation(options) {
var timeOutAnimation = options.animationDuration || 15;
var backgroundColor = options.color ; // this argument will be always present, so no default.
//more code...
}

and this is the call (I use a php code for example purposes) 这就是调用(出于示例目的,我使用了php代码)

$(document).ready(function(){
    var opt = {
        animationDuration: '<?php echo $_GET['stopAnimationAfter'] ?>', //could be a number, or nothing.
            color: 'black'
        }
    playAnimation(opt);     
});

the problem is that the argument is passed and it seams that it never falls on the default value. 问题在于传递了参数,并且它暗示它永远不会落在默认值上。 I can't change the way the function is called (ie checking the avialability of the "get" parameter and build the function call accordingly, I must find a way to test the arguments inside my javascript. 我无法更改函数的调用方式(即检查“ get”参数的可用性并相应地构建函数调用,我必须找到一种方法来测试javascript中的参数。

is there a safe way to do so, like options.animationDuration === "undefined" (doens't work) or something? 有没有安全的方法,例如options.animationDuration ===“未定义”(无效)或其他方法?

SOLUTION: putting ' ' around each argument in the call, makes the argument be full or empty accordingly. 解决方案:在调用中的每个参数周围加上“”,使参数相应地变满或变空。 and then i can test them. 然后我可以测试它们。

You can use: 您可以使用:

function playAnimation(options) {
    options = options || {}
    var timeOutAnimation = options.animationDuration || 15;
    var color = options.color;
}

To set options to an empty object if it doesn't exist. 将选项设置为空对象(如果不存在)。 You can also check for undefined like this if you want: 您还可以根据需要检查未定义,例如:

if(typeof options === "undefined") {
    // options not passed
}

Here is a fiddle which demonstrates. 这是一个小提琴 ,进行了演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM