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

JavaScript中变量为何显示undefined?代码问题排查求助

问题排查与解决方案

嘿,我来帮你理清这个问题!你遇到的showContact和list都是undefined的情况,核心原因其实很简单——你误用了console.log()的返回值。

问题拆解

  1. console.log()的返回值是undefined
    console.log()的作用是在控制台打印内容,但它本身没有返回任何有效数据(或者说返回的就是undefined)。你把console.log(contacts.name[i] + " " + contacts.surname[i])的结果赋值给showContact,这就导致每次循环里showContact都会被设置成undefined,最后自然也不会是你期望的"Jane Doe"。

  2. list数组被填充了undefined
    同理,你把showContact(也就是undefined)赋值给list[i],所以整个数组里的元素全都是undefined,而不是你想要的联系人字符串。

修正后的代码

我们只需要先拼接好联系人字符串,再用console.log()输出,同时把拼接后的字符串赋值给变量就可以了:

var contacts = { name:["John", "Jane"], surname:["Smith", "Doe"] } 
var list=[]; 
var showContact=""; 
var manager = prompt("Welcome to your contacts manager!\nEnter a number for:\n1: List contacts\n2: Add a contact\n0: Exit"); 
if (manager === "1") { 
  // 用let声明i,避免全局变量污染
  for (let i=0; i<contacts.name.length && i<contacts.surname.length; i++){ 
    // 先拼接完整姓名
    const fullName = contacts.name[i] + " " + contacts.surname[i];
    // 再输出到控制台
    console.log(fullName);
    // 将拼接好的字符串赋值给变量
    showContact = fullName;
    list[i] = fullName; 
  } 
} 
console.log(showContact); // 现在会输出 "Jane Doe"
console.log(list); // 现在会输出 ["John Smith", "Jane Doe"]

额外小建议

  • 循环里的i最好用let声明,这样它的作用域只在循环内部,不会意外污染全局变量。
  • 如果后续要扩展功能,比如添加联系人,记得要同时给contacts.name和contacts.surname数组push新元素,保持两个数组长度一致,避免循环时出现数据不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:28:00