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

JavaScript中Switch语句无法加载数据问题:能否在Switch中使用逻辑与&&?代码初始正常后突然失效无报错

Fixing Your Switch Statement & Unexpected Stopping Issue

Hey there! Let's break down your problems and fix the kinks in your code step by step.

1. Can you use the logical AND (&&) operator in a Switch statement?

Short answer: Not in the way you’re attempting right now.

The switch statement works by evaluating a single expression, then matching its exact result against your case values. If you tried using && directly in the switch expression (like switch(person.Status && person.Country)), the result would be a boolean (true or false), which will never match string cases like "confirmed".

If you do need to check multiple conditions in a switch, you can set the switch expression to true, then define your conditional logic inside the cases:

switch(true) {
  case person.Status === "confirmed" && person.Country === "England":
    results.confirmedEngland++;
    break;
  case person.Status === "suspected":
    results.suspected++;
    break;
}

But for your use case—tracking independent metrics (status for case types, country for England counts)—it’s way cleaner to handle these with separate, straightforward checks instead of forcing them into one switch.

2. Why does your code stop working after a few minutes (with no errors)?

Your code has two critical issues that lead to this silent failure:

  • Broken switch logic: You’re using the bitwise AND (&) instead of logical AND (&&), and combining person.Status and person.Country in the switch expression makes no sense here. This means none of your cases ever actually match, so your counts stay stuck at 0 (the initial values). Any "initial working" behavior was likely a fluke from how the data loaded early on.
  • No error handling for fetch: If the API call fails (network drops, rate limits, or the API returns an error status), your async code will fail silently because you have no try/catch blocks to catch and log issues.

Fixed Code

Here’s the corrected version with proper logic, error handling, and robust DOM updates:

const url = "https://raw.githubusercontent.com/globaldothealth/monkeypox/main/latest.json";

async function getData() {
  try {
    const response = await fetch(url);
    // Validate the API response before parsing
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Failed to load data:", error);
    // Return empty array to prevent downstream crashes
    return [];
  }
}

function getResults(data) {
  const results = {
    confirmed: 0,
    suspected: 0,
    England: 0,
  };

  data.forEach((person) => {
    // Track confirmed/suspected cases from Status
    if (person.Status === "confirmed") {
      results.confirmed++;
    } else if (person.Status === "suspected") {
      results.suspected++;
    }

    // Track England cases from Country
    if (person.Country === "England") {
      results.England++;
    }
  });

  return results;
}

(async function () {
  try {
    const data = await getData();
    const results = getResults(data);
    
    console.log(
      `${results.confirmed} confirmed cases\n${results.suspected} suspected cases.`
    );
    
    // Safely update DOM elements (check if they exist first)
    const vocsEl = document.getElementById("vocs");
    if (vocsEl) vocsEl.innerHTML = results.confirmed;
    
    const voxsusEl = document.getElementById("voxsus");
    if (voxsusEl) voxsusEl.innerHTML = results.suspected;
    
    const grEl = document.getElementById("gr");
    if (grEl) grEl.innerHTML = results.confirmed + results.suspected;
  } catch (error) {
    console.error("Error running the app:", error);
  }
})();

Key Fixes Explained

  • Replaced broken switch with clear conditionals: Separated checks for Status and Country since they’re independent metrics—this makes the logic easy to read and debug.
  • Added full error handling: Wrapped fetch calls and main execution in try/catch blocks, plus added a check for response.ok to catch HTTP errors. Now you’ll see clear error messages in the console if something goes wrong.
  • Safe DOM updates: Added checks to ensure elements exist before modifying their innerHTML, preventing unexpected DOM-related crashes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:13:11