在这里,我创建了一个数组来打印输出,但是第二个输出没有给出一个有效的结果,就像我想要的I work as a Web Dev in Ind.
一样,但是它打印了I work as a Sam in 27.
。所以,我需要改变这个程序的什么?
const arr = [
(name, age) => {
console.log(`My name is ${name} and I am ${age} years old.`);
},
(job, city) => {
console.log(`I work as a ${job} in ${city}.`);
}
];
for (let i = 0; i < arr.length; i++) {
arr[i]("Sam", 27, "Web Dev", "Ind");
}
要获得想要的效果,可以使用解构:
const arr = [
({name, age}) => {
console.log(`My name is ${name} and I am ${age} years old.`);
},
({job, city}) => {
console.log(`I work as a ${job} in ${city}.`);
}
];
for (let i = 0; i < arr.length; i++) {
arr[i]({ name: "Sam", age: 27, job: "Web Dev", city: "Ind"});
}
解构允许每个函数决定从传递的对象中提取哪些属性。您可以添加另一个函数:
const arr = [
({name, age}) => {
console.log(`My name is ${name} and I am ${age} years old.`);
},
({job, city}) => {
console.log(`I work as a ${job} in ${city}.`);
},
({city, age}) => {
console.log(`At ${age} years old, I find ${city} to be a lot of fun.`);
}
];
for (let i = 0; i < arr.length; i++) {
arr[i]({ name: "Sam", age: 27, job: "Web Dev", city: "Ind"});
}
您将所有4个参数传递给每个函数,该函数只需要2个参数。
在你的代码中:
for (let i = 0; i < arr.length; i++) {
arr[i]("Sam", 27, "Web Dev", "Ind");
}
基本上运行的是这两个函数调用:
arr[0]("Sam", 27, "Web Dev", "Ind")
arr[1]("Sam", 27, "Web Dev", "Ind")
你想要运行的是:
arr[0]("Sam", 27)
arr[1]("Web Dev", "Ind")
所以你必须去传递你的参数,或者用一种不同的方式执行你的函数。