开发者

how to call a function when parameter is not needed? what is the correct way

this should be fairly simple, but want to make sure...

function load_img(src, alt, el, other_src) {

// check if other_src exists, not null, defined, not empty, etc...

}

//call the function
load_img(src, alt, '#zoom-cover');

Is that the ok way to call the function when a parameter is not needed..

Should i write:

load_img(src, alt, '#zoom-cover', null);

or

load_img(src, alt, '#zoom-cover', '');

is there something similar like php

load_img(src, alt, '#zoom-cover', other_src='default value');

and... how do i check, in the function, that other_src exists, is defined, has a valid value, is not null or empty 开发者_StackOverflow中文版string?


This is fine

load_img(src, alt, '#zoom-cover');

If you want a default value to represent other_src when the parameter is not passed or null then do this:

function load_img(src, alt, el, other_src) {
  if (!other_src) {
    other_src = "mydefaultvalue"
  }
}

or something like this if you want the default value to represent other_src when the parameter is just not passed.

function load_img(src, alt, el, other_src) {
  if (typeof(other_src) === "undefined") {
    other_src = "mydefaultvalue"
  }
}


Just omit the extra parameters.

If you want to supply a default, use

other_src = other_src || 'default value';

in the top of your function, although this isn't appropriate if the original value could legitimately be "falsey", in which case:

if (typeof other_src === 'undefined') {
    other_src = 'default value';
}


In JS, if you don't pass a parameter, the local variable gets an 'undefined' type. so you can call the function without all the parameters.

load_img(src, alt, '#zoom-cover');


You can just omit the last argument if it is not needed. With the example you've given, that'd be:

load_img(src, alt, '#zoom-cover');

About your second question, you could simply do something like:

if(typeof other_src === 'undefined') {
    ...
}

JavaScript does not have named arguments ("like php"). Instead, though, you could pass in an object, like:

load_img(src, alt, '#zoom-cover', {other_src: 'something'});

This is a technique commonly used by jQuery Plugins.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜