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

JavaScript判断对象键存在性:动态调整问卷prompt答案选项

检查对象是否包含指定键并应用到问卷场景的解决方案

问题说明

你开发的问卷通过prompt()展示,后续问题依赖用户回答。每个问题包含必填的answer_1和可选的answer_2,但当前代码仅能处理存在answer_2的情况,没有answer_2时会报错。需要实现:

  • 存在answer_2时,prompt默认值显示answer_1.text / answer_2.text
  • 不存在answer_2时,prompt默认值仅显示answer_1.text
  • 同时正确处理两种场景下的用户回答判断,避免报错

检查对象是否包含指定键的常用方法

在JavaScript中,判断对象是否包含某个键可以用以下几种方式:

  • in操作符:'answer_2' in question,检查键是否存在于对象或其原型链中
  • hasOwnProperty()方法:question.hasOwnProperty('answer_2'),仅检查对象自身是否包含该键
  • 直接判断属性是否为undefined:question.answer_2 !== undefined,适用于属性不会被显式设为undefined的场景

修改后的完整代码

const questions = [{
    id: "1",
    question: "q1",
    answer_1: {
      text: "a1",
      next_question: "2",
    },
    answer_2: {
      text: "a2",
      next_question: "3",
    },
  },
  {
    id: "2",
    question: "q2",
    answer_1: {
      text: "a1",
      next_question: "",
    },
  },
  {
    id: "3",
    question: "q3",
    answer_1: {
      text: "a1",
      next_question: "",
    },
    answer_2: {
      text: "a2",
      next_question: "4",
    },
  },
  {
    id: "4",
    question: "q4",
    answer_1: {
      text: "a1",
      next_question: "",
    },
  },
];

function quiz({ question, answer_1, answer_2 }) {
  // 构建prompt的默认提示文本
  let defaultPrompt = answer_1.text;
  if ('answer_2' in arguments[0]) {
    defaultPrompt += ` / ${answer_2.text}`;
  }

  const answer = prompt(`${question}`, defaultPrompt);
  let nextQuestion;

  // 处理用户回答
  if (answer === answer_1.text) {
    nextQuestion = answer_1.next_question;
  } else if (answer_2 && answer === answer_2.text) {
    nextQuestion = answer_2.next_question;
  } else {
    alert("无效回答");
  }

  if (nextQuestion) {
    quiz(questions.find((q) => q.id === nextQuestion));
  }
}

quiz(questions[0]);

关键修改点解释

  1. 动态构建默认提示文本:先初始化默认值为answer_1.text,再通过'answer_2' in arguments[0]检查当前问题对象是否包含answer_2键,存在则拼接answer_2.text
  2. 安全处理回答判断:判断answer_2是否存在后再进行文本匹配,避免answer_2为undefined时访问answer_2.text导致报错
  3. 严格相等判断:将原代码的==改为===,符合JavaScript最佳实践,避免隐式类型转换导致的意外问题

内容的提问来源于stack exchange,提问作者userName

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:15:34