Проблема создания булевой функции Repl.it для javascript - PullRequest
0 голосов
/ 28 декабря 2018

Я пытался найти ответы, чтобы узнать моё любительское понимание javascript.Работая внутри Repl.it для моего класса и для начинающего, я чувствую, что многое было сведено к экстремальным основам, что не помогает, когда я ищу решение.

ОРИГИНАЛЬНАЯ ПРОБЛЕМА ЕСТЬЧтобы сделать это:

// orderPizza takes in a boolean
// if it is true return the string 'cheese pizza'
// if not, return the string 'pepperoni pizza'
// Example: orderPizza(true) returns 'cheese pizza'

function orderPizza(vegetarian) {

}

Я пытался МНОГИЕ, МНОГИЕ различные комбинации, пытаясь выяснить, что я делал неправильно, и в этот момент я просто не понимаю, что к чему больше.Вот одна из моих последних догадок:

function (vegetarian) {
let orderPizza = vegetarian;
    if (orderPizza = vegetarian) {
        return ("Cheese Pizza!");
    } else {
        return ("Pepperoni Pizza!");
}
};
let newOrder = vegetarian
console.log(newOrder)

Приходит с ошибкой.Есть ли какие-то решения сообщества?

Ответы [ 2 ]

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

Ошибка в вашем коде - это просто использование вами знака равенства = вместо логического оператора == (равно)

https://www.w3schools.com/js/js_comparisons.asp

Если вы переписываете свой код какниже он будет работать:

function (vegetarian) {
    // this is you set orderPizza is vegetarian
    let orderPizza = vegetarian;
    // Comparison operators is '==' or '===' not '='. '=' is Assignment Operators
    if (orderPizza == vegetarian) {
        return ("Cheese Pizza!");
    } else {
        return ("Pepperoni Pizza!");
    }
};
// this is you set orderPizza is vegetarian not call function
// you can call function with name and parameter
// example: let newOrder = orderPizza(true)
let newOrder = vegetarian
console.log(newOrder)

С точки зрения вопроса и хорошего ответа на него:

function orderPizza (vegetarian){
    if (vegetarian == true){
        return 'cheese pizza'
    }
    return 'pepperoni pizza'
}

order1 = orderPizza(true)
order2 = orderPizza(false)

console.log(order1)
// will log 'cheese pizza'
console.log(order2)
// will log 'pepperoni pizza'

примечание: вам на самом деле не нужно использовать другое, потому что код будетдостигать

return 'pepperoni pizza' 

только если выражение if не находит переменную равной true.Функция может вернуться только один раз.Вы можете думать о возврате как о «ответе» функции.

Вы можете написать

if (vegetarian == true) {

или

if (vegetarian) {

, потому что выражение if будет оценивать содержимоеиз скобок.Если вегетарианец «правдив» (https://www.w3schools.com/js/js_booleans.asp), то вам не нужно сравнивать его с «истиной».

Однако в смысле строгого равенства сравнение подтвердит, что его значение истинно, а недругое истинное значение, например строка.

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

Добро пожаловать в Javascript.Но я думаю, вам нужно начать учить js снова с w3school js tutorial .Его легко выучить.

ОРИГИНАЛЬНАЯ ПРОБЛЕМА - ЭТО СДЕЛАТЬ:

// orderPizza takes in a boolean
// if it is true return the string 'cheese pizza'
// if not, return the string 'pepperoni pizza'
// Example: orderPizza(true) returns 'cheese pizza'

function orderPizza(vegetarian) {
     // check vegetarian is true
     if(vegetarian){
         return 'cheese pizza';
     }else{
         return 'pepperoni pizza';
     }
}

// when you call orderPizza(true). In your function parameter is true
console.log(orderPizza(true));

// when you call orderPizza(true). In your function parameter is false
console.log(orderPizza(false));

Ваши последние догадки таковы:

// your function not have name (function name is name you call function)
// example : function orderPizza(vegetarian). orderPizza is function name. vegetarian is parameter you send to in function 
function (vegetarian) {
    // this is you set orderPizza is vegetarian
    let orderPizza = vegetarian;
    // Comparison operators is '==' or '===' not '='. '=' is Assignment Operators
    if (orderPizza = vegetarian) {
        return ("Cheese Pizza!");
    } else {
        return ("Pepperoni Pizza!");
    }
};
// this is you set orderPizza is vegetarian not call function
// you can call function with name and parameter
// example: let newOrder = orderPizza(true)
let newOrder = vegetarian
console.log(newOrder)
...