admin管理员组

文章数量:1327978

If I have a number of functions that take json object parameters, does it make any difference whether I assign them to a variable before using them inside the function:

Function doSomething(data){
var abc = data;

abc.filter….etc.

}

Vs.

Function doSomething(data){

Data.filter….etc

}

is one way better than the other?

If I have a number of functions that take json object parameters, does it make any difference whether I assign them to a variable before using them inside the function:

Function doSomething(data){
var abc = data;

abc.filter….etc.

}

Vs.

Function doSomething(data){

Data.filter….etc

}

is one way better than the other?

Share Improve this question asked Nov 26, 2012 at 22:45 user1783490user1783490 3731 gold badge8 silver badges23 bronze badges 3
  • In your second code snipped, your parameter is "data" (lower-case "d") but the code references "Data" (upper-case "d"). JavaScript is case-sensitive. (Well also of course you used "Function" ...) – Pointy Commented Nov 26, 2012 at 22:48
  • 1 It is pletely redundant to do that. – Esailija Commented Nov 26, 2012 at 22:48
  • Pointy - it was a typo but thanks for noting that – user1783490 Commented Nov 26, 2012 at 23:11
Add a ment  | 

3 Answers 3

Reset to default 4

This makes no difference and it your example, the new variable is redundant. It is good practice not to create extra variables. It might be useful to do this if your JSON is heavily nested.

data = { foo: { bar: { baz: [] } } }

function doSomething(data) {
  var innerData = data.bar.baz;
  for(var i=0; i<innerData.length; i+) {
    // Whatever.
  }     
}

This will save you having to reference data.foo.bar.baz all the time.

Yes, it is better not to create the useless extra variable.

It is pletely redundant to create the abc variable in the first example.

Consider how it's really evaluated:

function doSomething() {
    var data = arguments[0];
    var abc = data; //why?
}

本文标签: javascript functions with json object parameterStack Overflow