开发者

How do I test a variable passed into a function?

Quick question, I'm trying to pass a value to a variable and then run a function if the variable was set to something specific. How do I do that?

I have the following example where I want to assign the value name to a form field if the variable type is set to 1.

function test(name,type) {
  if (type=1) {
    document.myform.name.value = name;
  }
}

and a link in the body of the html:

<a href="javascript:test('myname','1');">FILL IN MY NAME</a>

I also tried the following with no luck:

function test(name,type) {
  var checktype = type;
  if (checktype = 1) {
    document.myform.name.value = name;
  }
}

I'm pretty sure something like this is possible, just not sure w开发者_运维问答hat I'm doing wrong.


Try this:

function test(name,type) {
  var checktype = type;
  if (checktype == 1) {
    document.myform.name.value = name;
  }
}

You were missing ==


You want to use ==, not =. Using a single symbol will assign the value of 1 to the variable checktype, rather than testing for equality:

function test(name,type) {
  if (type == 1) {
    document.myform.name.value = name;
  }
}


To avoid this type errors try to do this..

function test(name,type) {
  if (1 == type) {
    document.myform.name.value = name;
  }
}

In this case, if you type by mistake, 1=type, then you get an error and you locate it right way.


If variable didn't pass to function argument, the argument address will be Null. Therefore you need to check the addresses with if statement inside your function. ie:

bool flag(int & value)
{
  if (&value == NULL) {
      return false;
  }
  else {
      return true;
  }
}


Javascript uses == for equality checks.


function test(name,type) {
  if (type === "1") {
    document.myform.name.value = name;
  }
}

No need to use an additional variable inside the function for storing the value. Also use ===' instead of==` if you know the type of the variable.

See Strict equal

Returns true if the operands are strictly equal (see above) with no type conversion.


You need to use a comparison operator instead of an assignment operator:

function test(name, type) {
  if (type == 1) {
    document.myform.name.value = name;
  }
}

If you’re using an assignment operator, the whole expression evaluates to the assigned value. That means type = 1 evaluates to 1 that is equal true and the branching condition is always fulfilled.


function test(name,type) {
  if (type==1) {
    document.myform.name.value = name;
  }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜