问题
for example in python:
def dfde(name,age):
print(age)
print(name)
print(age)
dfde(age=27,name="dfd")
will give a output as:
27
dfd
27
but samething in javascript will give the output as:
let dfde = function(name, age){
console.log(age);
console.log(name);
console.log(age);
}
dfde(age=27, name="dfd")
will give output as:
dfd
27
dfd
even arguments are passed as named arguments,
why is that?
回答1:
even arguments are passed as named arguments,
There are no named arguments.
dfde(age = 27, name = "dfd")
is the same as:
dfde(27, "dfd")
(Additionally age = 27
creates a new global variable age and assigns the value to it)
To use something like named arguments in js you have to pass an obiect literal and deconstruct that:
function dfde({name, age}) {
console.log(name, age);
}
dfde({ name: "dfd", age: 27 });
// Same as
dfde({ age: 27, name: "dfd" });
回答2:
This happens because there's no named parameters in JavaScript. It recognizes parameters by the order of precedence. So, you should do this:
let dfde = function(name, age){
console.log(age);
console.log(name);
console.log(age);
}
dfde(name="dfd", age=27) // it just declares variable to global scope as `var`
dfde("dfd", 27) // same as above
You can also, log the way the function is receiving the parameters using arguments
like this:
let dfde = function(name, age){
console.log(arguments); // no named parameters
}
dfde(name="dfd", age=27)
If you want to use something like named parameter refer this answer.
来源:https://stackoverflow.com/questions/51259580/why-order-of-parameter-remain-same-even-arguments-are-passed-as-named-arguments