Функция не может использовать строку, полученную из адресной строки, в качестве аргумента - PullRequest
1 голос
/ 06 августа 2020

Я перестраиваю веб-сайт, который содержит c введение персонажей в файтинг Tekken 7 . Я сохранил все символы и их данные в виде объектов и настроил функцию для отображения данных персонажа на веб-странице, приняв имя этого персонажа в качестве единственного аргумента.

/* DECLARATIONS */
// Profile
let charName = document.getElementById("char-name");
let charNickname = document.getElementById("nickname");

let charFlag = document.getElementById("flag");
let charImg = document.getElementById("image");

let charAge = document.getElementById("age");
let charCountry = document.getElementById("country");
let charFightingStyle = document.getElementById("fighting-style");
let charDebut = document.getElementById("first-appearance");

// Scores
let charOffense = document.getElementById("offense");
let charDefence = document.getElementById("defence");
let charRange = document.getElementById("range");
let charPunishment = document.getElementById("punishment");

let charGimmicks = document.getElementById("gimmicks");
let charExecution = document.getElementById("execution");
let charHurtbox = document.getElementById("hurtbox");

// Playstyle and Intro
let charPlaystyle = document.getElementById("playstyle");
let charIntro = document.getElementById("introduction");


/* DISPLAY FUNCTION */
const display = character => {
    charName.innerHTML = character.name;
    charNickname.innerHTML = character.nickname;

    charFlag.src = character.flag;
    charImg.src = character.image;

    charAge.innerHTML = character.age;
    charCountry.innerHTML = character.country;
    charFightingStyle.innerHTML = character.fightingStyle;
    charDebut.innerHTML = character.debut;

    charOffense.innerHTML = character.offense;
    charDefence.innerHTML = character.defence;
    charRange.innerHTML = character.range;
    charPunishment.innerHTML = character.punishment;

    charGimmicks.innerHTML = character.gimmicks;
    charExecution.innerHTML = character.execution;
    charHurtbox.innerHTML = character.hurtbox;

    charPlaystyle.innerHTML = character.playstyle;
    charIntro.innerHTML = character.introduction;
}

/* CHARACTER EXAMPLE */
// Jin Kazama
const jin = {
    // Profile
    name: "Jin Kazama",
    nickname: "The Child of Destiny",

    flag: "../img/flagicons/japan.svg",
    image: "../img/characters/jin.png",

    age: 21,
    country: "Japan",
    fightingStyle: "Traditional karate",
    debut: "<em>Tekken 3</em>",

    // Scores
    offense: 9,
    defence: 10,
    range: 8,
    punishment: 8,

    gimmicks: 3,
    execution: 3,
    hurtbox: 3,

    // Playstyle
    playstyle: "Versatile, keep-out, Mishima",
    introduction: "<p>Versatile character who performs at his best in the mid-range, armed with good poking, great counter hit tools, great damage output, variety in his throws and a unique parry that deals with all highs and mids except projectiles (fireballs). While his Mishima-style tools are not quite as effective as those of the out-and-out Mishima characters, he makes up for it with other situational moves that plug those weaknesses. He does, however, lack range on a few key punishers.</p>",
};

/* CALLING DISPLAY FUNCTION */
let params = (new URL(document.location)).searchParams;
let char = params.get("view");
display(char);

Код анализирует "просмотреть" параметр из адресной строки и должен возвращать его функции в качестве аргумента. Например, если в адресной строке указан URL-адрес .../guides/character.html?view=jin, код в идеале должен проанализировать значение jin и передать его обратно функции в качестве аргумента для отобразить это . Я даже протестировал аргумент char с console.log, чтобы убедиться, что значение было передано без каких-либо проблем, и он напечатал jin, как ожидалось.

Однако, когда код запускается сам по себе, он почему-то не может используйте значение в качестве аргумента и вместо этого возвращает неопределенный объект, при этом консоль показывает сообщение об ошибке GET [file path]/guides/undefined net::ERR_FILE_NOT_FOUND как , показанное здесь .

Может ли кто-нибудь помочь мне понять, почему это происходит? Я все еще изучаю некоторые внутренние механизмы JavaScript, так что я совершенно сбит с толку.

1 Ответ

0 голосов
/ 06 августа 2020

Вы очень близки к тому, чтобы получить это правильно. Я считаю, что проблема, с которой вы столкнулись, заключается в том, что вы ожидаете, что строка "jin" будет ссылаться на ваш const jin. Однако механизм рендеринга JS на самом деле работает не так - строка "jin" передается просто как строка, поэтому все ваши значения отображаются undefined - потому что строка "jin" имеет ни одно из свойств, которые вы ищете.

Будет записана переданная строка "jin", а затем несколько undefined:

const jin = {
    // Profile
    name: "Jin Kazama",
    nickname: "The Child of Destiny",

    flag: "../img/flagicons/japan.svg",
    image: "../img/characters/jin.png",

    age: 21,
    country: "Japan",
    fightingStyle: "Traditional karate",
    debut: "<em>Tekken 3</em>",

    // Scores
    offense: 9,
    defence: 10,
    range: 8,
    punishment: 8,

    gimmicks: 3,
    execution: 3,
    hurtbox: 3,

    // Playstyle
    playstyle: "Versatile, keep-out, Mishima",
    introduction: "<p>Versatile character who performs at his best in the mid-range, armed with good poking, great counter hit tools, great damage output, variety in his throws and a unique parry that deals with all highs and mids except projectiles (fireballs). While his Mishima-style tools are not quite as effective as those of the out-and-out Mishima characters, he makes up for it with other situational moves that plug those weaknesses. He does, however, lack range on a few key punishers.</p>",
};

const display = character => {
    console.log(character);
    console.log(character.name);
    console.log(character.nickname);

    console.log(character.flag);
    console.log(character.image);

    console.log(character.age);
    console.log(character.country);
    console.log(character.fightingStyle);
    console.log(character.debut);

    console.log(character.offense);
    console.log(character.defence);
    console.log(character.range);
    console.log(character.punishment);

    console.log(character.gimmicks);
    console.log(character.execution);
    console.log(character.hurtbox);

    console.log(character.playstyle);
    console.log(character.introduction);
}

display('jin');

Так как исправить? Самая простая ставка, скорее всего, - создать гигантский объект конфигурации с именем characters, который содержит свойство для имени каждого персонажа, которое содержит объект со всеми их свойствами. Используя объект, вы можете ссылаться на символ в виде строки, чтобы получить объект со всеми свойствами:

Отображает весь объект, за которым следуют отдельные характеристики / свойства:

const characters ={
    jin: {
        // Profile
        name: "Jin Kazama",
        nickname: "The Child of Destiny",

        flag: "../img/flagicons/japan.svg",
        image: "../img/characters/jin.png",

        age: 21,
        country: "Japan",
        fightingStyle: "Traditional karate",
        debut: "<em>Tekken 3</em>",

        // Scores
        offense: 9,
        defence: 10,
        range: 8,
        punishment: 8,

        gimmicks: 3,
        execution: 3,
        hurtbox: 3,

        // Playstyle
        playstyle: "Versatile, keep-out, Mishima",
        introduction: "<p>Versatile character who performs at his best in the mid-range, armed with good poking, great counter hit tools, great damage output, variety in his throws and a unique parry that deals with all highs and mids except projectiles (fireballs). While his Mishima-style tools are not quite as effective as those of the out-and-out Mishima characters, he makes up for it with other situational moves that plug those weaknesses. He does, however, lack range on a few key punishers.</p>",
    }
};

const display = character => {
    console.log(character);
    console.log(character.name);
    console.log(character.nickname);

    console.log(character.flag);
    console.log(character.image);

    console.log(character.age);
    console.log(character.country);
    console.log(character.fightingStyle);
    console.log(character.debut);

    console.log(character.offense);
    console.log(character.defence);
    console.log(character.range);
    console.log(character.punishment);

    console.log(character.gimmicks);
    console.log(character.execution);
    console.log(character.hurtbox);

    console.log(character.playstyle);
    console.log(character.introduction);
}

display(characters['jin']);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...