JavaScript, возвращающий NaN переменную, возвращающую неопределенное - PullRequest
0 голосов
/ 01 декабря 2018

В данный момент я изучаю javascript, у меня 2 проблемы с одним и тем же кодом.

1) В фигурных скобках, если я помещаю один в верхней части кода под var Character function.Я могу заставить команду changedXPos(); работать в консоли, если я этого не сделаю, я получаю changedXPos(); эту ошибку "Uncaught ReferenceError: changeXPos не определено в: 1: 1" Я не уверен почему.

2) В функции changedXPos при выполнении кода я получаю значение как NaN.Я использовал отладчик, и я вижу, что весь экземпляр xPos не определен.Если я даю xPos = 20, то код работает нормально, поэтому я знаю, что xPos по какой-то причине не ведет себя так, как должно, я просто не уверен, почему.

Я добавил комментарии в кодчтобы показать, где проблема.Спасибо за ваше время

var Character = function(name, xPos, yPos) {
  this.name = name;
  this.xPos = xPos;
  this.yPos = yPos;

  //} this bracket is not commentented out code works, by changedXPos(); in    console but xPos is still undefined

  //create instance of Character
  var ron = new Character("Ronald", 55, 30);
  var jil = new Character("Jill", 25, 45);
  var jas = new Character("Jasmine", 16, 85);

  //create arrary of instance Character
  var characterArray = [ron, jil, jas];

  //create for loop to loop through characterArray
  for (i = 0; i < characterArray.length; i++) {
    console.log(characterArray[i]);
  }

  this.information = function() {

    "My name is: " + this.name + " My X position is: " + this.xPos + " My Y  position is: " + this.yPos;
  }

  this.changedXPos = function(value) {
    // change the x position here
    //debugger;
    var xPos = this.xPos; // if i take this var out i get xPos is undefined 
    //var value = isNaN(parseInt(xPos)) ? 0 : parseInt(xPos);
    for (i = 0; i < characterArray.length; i++) {
      value = xPos + 20;
      console.log(value); // value is NaN or xPos is undefined
    }
  }

  this.changedYPos = function(value) {
    // change the y position here
  }

  Character.prototype.toString = function toString() {
    //var info = // character's name and current position on the screen
    //return info;
  };
} // with this bracket coded out above function is out of code block

Ответы [ 2 ]

0 голосов
/ 01 декабря 2018

Посмотрите на приведенный ниже код и проверьте, хотите ли вы этого достичь.

function Character(name, xPos, yPos) {
    this.name = name;
    this.xPos = xPos;
    this.yPos = yPos;

    this.changedXPos = function(value) {
        this.xPos = this.xPos + value;
    }
    this.changedYPos = function(value) {
        this.yPos = this.yPos + value;
    }
    this.information = function() {
        return "My name is: " + this.name + " My X position is: " + this.xPos + " My Y  position is: " + this.yPos;       
    }
}

var ron = new Character("Ronald", 55, 30);
var jil = new Character("Jill", 25, 45);
var jas = new Character("Jasmine", 16, 85);
var characterArray =[ron,jil,jas];

function changedXPosition(value) {
    for(i = 0; i < characterArray.length; i++){
        characterArray[i].changedXPos(value);
    }
}

function changedYPosition(value){
    for(i = 0; i < characterArray.length; i++){
        characterArray[i].changedYPos(value);
    }
}

changedXPosition(20);
changedYPosition(30);

for(i = 0; i < characterArray.length; i++){
    console.log(characterArray[i].information());
}
0 голосов
/ 01 декабря 2018

Похоже, это то, что вы хотите исправить свой код.Чтобы обойти вас, вы создали функцию конструктора Character, а затем создали 3 ее экземпляра с именами ron, jil и jas

Затем вы добавили несколько функций в цепочку прототипов Character, переопределяя метод toString.а также распечатывает ваш пользовательский метод.

Запускаемый скрипт при переполнении стека, кажется, печатает весь объект, но если вы запускаете его в коде, он должен работать.

function Character (name, xPos, yPos) {
  this.name = name;
  this.xPos = xPos;
  this.yPos = yPos;
}

var ron = new Character("Ronald", 55, 30);
var jil = new Character("Jill", 25, 45);
var jas = new Character("Jasmine", 16, 85);

var characterArray = [ron, jil, jas];

Character.prototype.changedXPos = function(value) {
  this.xPos = value;
}

Character.prototype.changedYPos = function(value) {
  this.yPos = value;
}

Character.prototype.toString = function() {
  return "My name is: " + this.name +
    " My X position is: " + this.xPos +
    " My Y  position is: " + this.yPos;
};

//create for loop to loop through characterArray
for (i = 0; i < characterArray.length; i++) {
  console.log(characterArray[i]);
}
...