admin管理员组文章数量:1416072
Is it possible in JavaScript to define a variable name with a function parameter?
Here is my jsFiddle. In the example below, I would like varB
to be defined as null
when it is passed through makeNull(varName)
:
var varA = undefined;
if (varA == undefined) {
varA = null;
}
var varB = undefined;
makeNull(varB);
function makeNull(varName) {
if (varName == undefined) {
varName = null;
}
}
alert (varA + ' | ' + varB);
Is it possible in JavaScript to define a variable name with a function parameter?
Here is my jsFiddle. In the example below, I would like varB
to be defined as null
when it is passed through makeNull(varName)
:
var varA = undefined;
if (varA == undefined) {
varA = null;
}
var varB = undefined;
makeNull(varB);
function makeNull(varName) {
if (varName == undefined) {
varName = null;
}
}
alert (varA + ' | ' + varB);
Share Improve this question asked Oct 2, 2012 at 14:59 Mark RummelMark Rummel 2,95010 gold badges38 silver badges52 bronze badges 4- You appear to be trying to break encapsulation by changing the bindings in another higher scope. Why? Even if there is a solution, this isn't good software practice. – Francis Avila Commented Oct 2, 2012 at 15:01
- I agree with Francis, but there's nothing wrong with creating functions to modify objects or variables. You should just be explicit about what you pass in, and what you return. Maybe something like this? jsfiddle/zVM9M/2 – Daniel Attfield Commented Oct 2, 2012 at 15:02
-
@FrancisAvila I'm getting the value of multiple checkboxes via jQuery. The ones that are checked = 1 the ones that aren't checked are
undefined
, but I need them to benull
. For example: checkbox1 = 1, checkbox2 = 1, checkbox3 = null. – Mark Rummel Commented Oct 2, 2012 at 15:21 - 1 If you represent all the checkboxes as an array, you can pass the entire array to your makeNull function, and it can set the undefined elements to null. – Barmar Commented Oct 2, 2012 at 16:27
3 Answers
Reset to default 2If you are trying to define a variable with a function parameter then you either want to use an array or an object.
JavaScript doesn't provide "call by reference" parameters. When you call a function, it receives the values of the argument expressions, not references to the variables that were in the expressions. So it can't modify the bindings of those variables.
If you want to do something like this, you can use containers and labels, e.g.
function makeNull(obj, label) {
if (obj[label] === undefined) {
obj[label] = null;
}
}
var varB = { abc: undefined }
makeNull(varB, 'abc');
you can pass a variable (defined as 'undefined') to a function and set its value.
http://jsfiddle/AwnVN/
本文标签: JavaScript Define variable name with function parameterStack Overflow
版权声明:本文标题:JavaScript: Define variable name with function parameter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745245904a2649554.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论