数组输出在 JS 中没有给出正确的结果

问题描述 投票:0回答:3

在这里,我创建了一个数组来打印输出,但第二个输出没有给出有效结果,就像我想要的

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");
}

javascript arrays data-structures logic
3个回答
0
投票

每个函数都需要传递单独的参数。您可以像这样将参数存储在另一个数组中:

const funcs = [
  (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}.`);
  }
];
let args = [["Sam", 27], ["Web Dev", "Ind"]];
for (let i = 0; i < funcs.length; i++) funcs[i](...args[i]);

另见:Spread Syntax.


0
投票

您将所有 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")

所以你将不得不着手传递你的参数,或者以不同的方式执行你的函数。


0
投票

要得到你想要的效果,你可以使用解构:

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"});
}

© www.soinside.com 2019 - 2024. All rights reserved.