You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据chosen变量简化对象数组的解构输出逻辑?

问题:简化根据chosen变量解构数组元素的代码

原始数据与需求

现有对象数组:

let myFriends = [
  { title: "Osama", age: 39, available: true, skills: ["HTML", "CSS"] },
  { title: "Ahmed", age: 25, available: false, skills: ["Python", "Django"] },
  { title: "Sayed", age: 33, available: true, skills: ["PHP", "Laravel"] },
];

以及变量:

let chosen = 2;

需求:根据chosen变量的值(1、2、3),对应解构数组的第1、2、3个元素(数组索引从0开始,对应索引0、1、2),输出如下格式的信息:

// 当chosen === 1时
"Osama"
39
"Available"
"CSS"

// 当chosen === 2时
"Ahmed"
25
"Not Available"
"Django"

// 当chosen === 3时
"Sayed"
33
"Available"
"Laravel"

已实现的Switch版本

已通过switch语句实现功能:

switch (chosen) {
  case 1:
    const { title: t1, age: a1, available: av1, skills: s1 } = myFriends[0];
    const [h1, c1] = myFriends[0].skills
    console.log(t1)
    console.log(a1)
    console.log(av1 ? "Available" : "Not Available")
    console.log(c1)
    break;
  case 2:
    const { title: t2, age: a2, available: av2, skills: s2 } = myFriends[1];
    const [h2, c2] = myFriends[1].skills
    console.log(t2)
    console.log(a2)
    console.log(av2 ? "Available" : "Not Available")
    console.log(c2)
    break;
  case 3:
    const { title: t3, age: a3, available: av3, skills: s3 } = myFriends[2];
    const [h3, c3] = myFriends[2].skills
    console.log(t3)
    console.log(a3)
    console.log(av3 ? "Available" : "Not Available")
    console.log(c3)
}

问题与修改方案

尝试用函数简化但未生效,原函数代码:

function chosenPerson(chosen) {
  const { title: t, age: a, available: av, skills: s } = myFriends[`${chosen}`];
  const [h, c] = myFriends[`${chosen}`].skills
  console.log(t)
  console.log(a)
  console.log(av ? "Available" : "Not Available")
  console.log(c)
};

chosenPerson();

问题出在三个地方:

  • 调用函数时未传入chosen参数,导致函数内部的chosen为undefined
  • 数组索引错误:chosen的值是1、2、3,而数组索引是0、1、2,需要用chosen - 1匹配正确的数组元素,且无需转字符串,直接用数字索引即可
  • 解构重复取值:可直接从解构出的skills里获取第二个元素,无需再次访问数组

修改后的函数如下:

function chosenPerson(chosen) {
  // 计算正确的数组索引
  const index = chosen - 1;
  // 一次性解构出需要的属性,包括skills的第二个元素
  const { title, age, available, skills: [, secondSkill] } = myFriends[index];
  console.log(title);
  console.log(age);
  console.log(available ? "Available" : "Not Available");
  console.log(secondSkill);
};

// 调用时传入chosen变量
chosenPerson(chosen);

说明

  1. 用chosen - 1将1-3的输入转换为数组的0-2索引,匹配正确的元素
  2. 解构时直接从skills里提取第二个元素(用, secondSkill跳过第一个元素),简化代码
  3. 调用函数时必须传入chosen参数,确保函数能获取到目标值

内容的提问来源于stack exchange,提问作者حسان ونس

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:35:29