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

Switch Case递归调用cityname函数报错:TypeError: cityname is not a function

问题分析与解决方案

错误原因

  1. 变量名冲突:getWeatherData函数的第一个参数命名为cityname,和全局的cityname()函数同名。在then回调内部,cityname指向的是传入的字符串参数而非全局函数,调用时自然会抛出TypeError: cityname is not a function。
  2. 语法错误:cityname()函数末尾多了一个多余的}),导致代码无法正常解析。

修复后的代码

import axios from "axios";
import readlineSync from "readline-sync";

cityname();

function cityname() {
  const apiKey = 'xyz';
  var name = readlineSync.question(`Enter City Name:\n`);
  return getWeatherData(name, apiKey);
}

function getWeatherData(cityName, apiKey) {
  axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}`)
    .then((res) => {
      let data = res.data;
      var options = readlineSync.questionInt(`Select an option below for ${cityName}\n
        1. Change City\n
        0. Exit\n`);

      switch(options) {
        case 1: 
          cityname();
          break;
        case 0: 
          console.log('Exiting the program...');
          break;
        default:
          console.log('Invalid option. Please try again.');
          getWeatherData(cityName, apiKey);
          break;
       }
    })
    .catch(err => {
      console.log('Failed to fetch weather data, please check city name.');
      cityname();
    });
}

关键修改点

  • 将getWeatherData的第一个参数从cityname改为cityName,避免和全局函数名冲突。
  • 删除cityname()函数末尾多余的}),修复语法错误。
  • 在case 1中添加break,防止逻辑穿透到case 0。
  • 增加catch块处理API请求失败的情况,提升程序健壮性。
  • 无效选项时重新调用getWeatherData,让用户可再次选择。

内容的提问来源于stack exchange,提问作者Mohammed Naseer Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:35:54