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

JS新手求助:实现电话簿查询时无法判断姓名是否存在

Fixing Your JavaScript Phonebook Lookup Issue

Hey there! Let's walk through what's going wrong with your code and fix it up properly. I can see you're new to JavaScript and trying to build a phonebook with lookups—great start! The main problem here is how you're storing your entries and checking if a name exists.

What's Wrong With Your Current Code?

  1. Using an Array Like an Object: You declared d = [] (an array) but then used it like an object by assigning properties with d[x[0]] = x[1]. The includes() method for arrays checks if a value exists as an element in the array (like d[0], d[1]), not if a property/key exists on the array object. That's why d.includes(name) never works.
  2. Inefficient Input Handling: You're splitting the input string into lines every time you need a line, and using splice() which modifies the original array—this is messy and can lead to off-by-one errors.
  3. Unreliable Query Loop: Using a try/catch block to detect when there's no more input isn't the right approach here. It's better to process all query lines directly from the input.

Solution 1: Use a Plain Object (Simple Approach)

We'll store the phonebook entries in a regular JavaScript object, which acts like a hash map. We'll also split the input into lines once to make processing easier:

function processData(input) {
    // Split input into lines, filter out empty lines to avoid edge cases
    const lines = input.split('\n').filter(line => line.trim() !== '');
    const n = parseInt(lines[0]);
    const phoneBook = {};

    // Populate the phone book with entries
    for (let i = 1; i <= n; i++) {
        const [name, number] = lines[i].split(' ');
        phoneBook[name] = number;
    }

    // Process each query
    for (let i = n + 1; i < lines.length; i++) {
        const queryName = lines[i].trim();
        // Check if the name exists as a property in the object
        if (phoneBook.hasOwnProperty(queryName)) {
            console.log(`${queryName}=${phoneBook[queryName]}`);
        } else {
            console.log('Not found');
        }
    }
}

Solution 2: Use Map (Follows the Dictionary/Map Requirement)

If you want to use a proper Map data structure (which is exactly what the problem asks for), here's how to do it. Maps have built-in methods for checking keys and getting values:

function processData(input) {
    const lines = input.split('\n').filter(line => line.trim() !== '');
    const n = parseInt(lines[0]);
    const phoneBook = new Map();

    // Add entries to the Map
    for (let i = 1; i <= n; i++) {
        const [name, number] = lines[i].split(' ');
        phoneBook.set(name, number);
    }

    // Handle queries
    for (let i = n + 1; i < lines.length; i++) {
        const queryName = lines[i].trim();
        // Use Map's built-in `has()` method to check for the key
        if (phoneBook.has(queryName)) {
            console.log(`${queryName}=${phoneBook.get(queryName)}`);
        } else {
            console.log('Not found');
        }
    }
}

Key Fixes Explained:

  • Single Input Split: We split the input into lines once, so we don't repeat work or mess with array modifications.
  • Proper Existence Check: For objects, we use hasOwnProperty() to safely check if the name is a direct property (avoids issues with inherited properties). For Maps, we use the dedicated has() method.
  • Clear Query Loop: We directly loop through the remaining lines after the phonebook entries—no need for error handling just to detect the end of input.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:42:49