Проблема с методом объекта JS, не меняющим логическое свойство - PullRequest
0 голосов
/ 28 ноября 2018

мой первый вопрос здесь, и я только изучаю JS, поэтому наберитесь терпения.

Я пытаюсь создать объект под названием крыса, где вы можете изменить, есть ли у него хвост или нет.Если у крысы есть хвост, и нет изменений (то есть несчастного случая), то он все равно должен иметь свой хвост.В других случаях у него не должно быть хвоста (поэтому, если у него нет хвоста и есть авария, у него все еще нет хвоста).Я хочу, чтобы логика была такой:

логика

В настоящее время у меня есть следующий код:

function animal(name, age, tail) {
    this.name = name;
    this.age = age;
    this.tail = tail;
    this.changeTail = function (tail) {
        tail=true ? this.tail=tail : this.tail=false;
    }
}

var rat = new animal("Arthur", 2, false);
rat.changeTail(true);

document.write(rat.name + '<br />' + rat.age + '<br />has tail: ' + rat.tail);

Проблема в том, что результат не следует логике.Я ожидаю, что он вернет false, когда rat.tail установлен на false, а changeTail равен true (потому что крыса не может отрастить другой хвост) - но вместо этого он возвращает true.

Чего мне не хватает?

Ответы [ 2 ]

0 голосов
/ 28 ноября 2018

Ошибка вашего кода заключается в том, как вы используете троичный оператор , один из моих избранных .

Введение в псевдокоде выглядит следующим образом:

variable_getting_value = boolean_expression ? value_returned_if_true : value_returned_if_false;

Эквивалент этого многословия:

if(boolean_expression)
    return value_returned_if_true;
else
    return value_returned_if_false;

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

с

tail=true ? this.tail=tail : this.tail=false;

до

this.tail= this.tail ? tail : this.tail;

Видите разницу?Вы были на правильном пути, так что хорошая работа!Кроме того, я добавил в код соответствующую переменную, которая является this.tail .В противном случае вы изменяете только значение параметра, переданного в функцию.

/*
If the rat has its tail and there is no change (i.e. accident), then it should still have its tail. In the other instances it should not have its tail (so if it's got no tail and has an accident, it still has no tail). 
*/

function animal(name, age, tail)
{
	this.name = name;
	this.age = age;
	this.tail = tail;
	this.changeTail = function (tail)
	{
		this.tail= this.tail ? tail : this.tail;
	}
}

var rat = new animal("Arthur", 2, false);
rat.changeTail(true);

document.write(rat.name + '<br />' + rat.age + '<br />has tail: ' + rat.tail);

По существу, в boolen_expression троичного оператора идет ограничение на то, что делать, имеет ли крыса изначально хвост или нет.Точно так же, если крыса попала в аварию и в будущем не имеет хвоста, вы не можете добавить ее к ней.Итак, если у крысы нет хвоста , она никогда не изменится, потому что если boolean_expression всегда будет возвращать False и value_returned_if_false всегда будет получать возврат, который будет False .Между тем, если this.tail равно True , как, например, при создании крысы со сказкой, тогда вы можете иметь возможность несчастного случая, если несчастный случай произойдет, какое бы значение вы ни выбрали.переданный в changeTail () будет новым значением для this.tail .

Потенциальные ловушки:

var rat = new animal("Arthur", 2, true);
rat.changeTail(false);

В этом кодевывод будет False , потому что вы передаете значение, переданное функции, как есть.Еще хуже, если вы передадите числовое значение, ваш this.tail внезапно станет также числом.

var rat = new animal("Arthur", 2, true);
rat.changeTail(5); 

Теперь rat.tail на самом деле 5 .Не совсем то, что ожидалось, верно?Я добавил фрагмент кода, в котором говорится об этом с некоторым вдохновением, так как не понимаю понятия между changeTail(true) changeTail(false) и «аварией».

/*
    If the rat has its tail and there is no change (i.e. accident), then it should still have its tail. In the other instances it should not have its tail (so if it's got no tail and has an accident, it still has no tail). 
    */

    function animal(name, age, tail)
    {
    	this.name = name;
    	this.age = age;
    	this.tail = tail;
    	this.changeTail = function (tail)
    	{
    		//Check if parameter is not actually boolean
        if (typeof tail != typeof true){
            throw "changeTail only accepts boolean values";
        }
        
        //If you got here, tail is a boolean value, but I don't really understand what should happen if tail is false, so I have taken some liberties with the following
        let accident_occurred = tail && true; 
        //The previous line will return true only if tail is true because of the &&
        //Only makes changes to tail if accident_occurred
        this.tail= this.tail && accident_occurred ? false : this.tail;
        //I put in a solid false value because I am assuming the tail parameter actually means that an accident occurred and you want the tail cut    
    	}
    }
    
    animal.prototype.toString = function()
{
    return this.name + '<br />' + this.age + '<br />has tail: ' + this.tail + '<br /><br />';
}

    var rat1 = new animal("Arthur", 2, false);
    rat1.changeTail(true);
    
    var rat2 = new animal("Rosy", 2, true);
    rat2.changeTail(false);
    
    document.write(rat1.name + " change tail true <br/><br/>");
    document.write(rat1);
    document.write(rat2.name + " change tail false <br/><br/>");
    document.write(rat2);
    
    document.write(rat1.name + " change tail false <br/><br/>");
    rat1.changeTail(false);
    document.write(rat1);
    
    document.write(rat2.name + " changet tail true <br/><br/>");
    rat2.changeTail(true);
    document.write(rat2);
0 голосов
/ 28 ноября 2018

function animal(name, age, tail)
{
	this.name = name;
	this.age = age;
	this.tail = tail;
	this.changeTail = function (tail)
	{
		this.tail=tail ? false: this.tail;
	}
}

var rat = new animal("Arthur", 2, true);   //initially, tail is intact
var mat = new animal("Matt", 3, false);    //initially, has not tail

console.log(rat.name + ' age: ' + rat.age + ', has tail: ' + rat.tail);
console.log(mat.name + ' age: ' + mat.age + ', has tail: ' + mat.tail);

rat.changeTail(true);                     // accident!
mat.changeTail(true);

console.log(rat.name + ' age: ' + rat.age + ', has tail: ' + rat.tail);
console.log(mat.name + ' age: ' + mat.age + ', has tail: ' + mat.tail);
function (tail) {
    tail=true ? this.tail=tail : this.tail=false;
}

Эта функция не возвращает никакого значения и не влияет на свойства экземпляра.Он действует только на параметр, которому он был передан (по значению, а не по ссылке).

Вот как это исправить:

  function (tail) {
         this.tail=tail ? false : this.tail;
    }
...