Javascript 是一种动态语言。相同的函数可以接受动态参数。有多种方法可以访问通过 2 个函数/构造函数传递的所有变量。
- 使用arguments。
- 使用可变参数或rest operator。
- rest 运算符和参数的混合。
这取决于您希望如何使用这些值。请参阅以下示例。
function DogArgs(name) {
this.name = name;
console.log(arguments); // array like structure [Arguments] { '0': 'Max', '1': 'Buddy' }
}
function DogRest(...names) {
this.name = names[0];
console.log(names); // Array [ 'Max', 'Buddy' ]
}
function DogPartialRest(name, ...others) {
this.name = name;
console.log(others); // Array [ 'Buddy' ]
}
var max1 = new DogArgs("Max", "Buddy");
var max2 = new DogRest("Max", "Buddy");
var max3 = new DogPartialRest("Max", "Buddy");
示例 1:使用参数
function sum() {
const values = Array.from(arguments); // convertin array, since arguments is not array
return values.reduce((sum, val) => (sum += val), 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4)); // 10
示例 2:使用 vaargs 或 rest 运算符。
function sum(...values) {
return values.reduce((sum, val) => (sum += val), 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4)); // 10
示例 3:rest 运算符和参数的混合
function Person(name, age, ...rest) {
this.name = name
this.age = age
this.salary = 0
if(rest.length) {
this.salary = rest[0]
this.address = rest[1] || ''
}
}
console.log(new Person("deepak", 30)) // Person { name: 'deepak', age: 30, salary: 0 }
console.log(new Person("deepak", 30, 2000)) // Person { name: 'deepak', age: 30, salary: 2000, address: '' }