对象javascript中未定义的布尔值

qncylg1j  于 2023-05-16  发布在  Java
关注(0)|答案(2)|浏览(156)

我尝试了下面的任务,但我坚持定义一个布尔值:
定义一个函数getWalletFacts,它接收一个钱包对象。
getWalletFacts应该返回一个句子,说明钱包的颜色和现金状态。
我尝试的代码

const hascash = Boolean();

let wallet ={
    color:"",
    hascash:true||false,
    write: function(sentence){
        console.log(sentence);
    }
};
function getWalletFacts(wallet){
    let sentence= "my wallet is " + wallet.color+ " and  " + wallet.hascash; 
    return sentence;
}

每当我检查我的答案,它告诉我,hascash是未定义的,即

Expected: "My wallet is Black and has cash"
        Received: "my wallet is Black and  undefined"

根据我对这个问题的理解,hascash接受布尔值

举例说明

const wallet = {
    color: "Black",
    hasCash: true
};

getWalletFacts(wallet); // => 'My wallet is Black and has cash'

const wallet2 = {
    color: "Grey",
    hasCash: false
};

getWalletFacts(wallet2); // => 'My wallet is Grey and does not have cash'
gwbalxhn

gwbalxhn1#

它是hasCash,而不是hascash-- JavaScript区分大小写。
您还需要一个条件式将true/false值转换为正确的英语。

function getWalletFacts(wallet) {
  let sentence = "my wallet is " + wallet.color + " and " + (wallet.hasCash ? "has cash" : "does not have cash");
  return sentence;
}

const wallet = {
    color: "Black",
    hasCash: true
};

console.log(getWalletFacts(wallet)); // => 'My wallet is Black and has cash'

const wallet2 = {
    color: "Grey",
    hasCash: false
};

console.log(getWalletFacts(wallet2)); // => 'My wallet is Grey and does not have cash'
i34xakig

i34xakig2#

function getWalletFacts(wallet) {
let money = " ";
if (wallet.hasCash === true) {
    money = "has cash";
}   else {
    money = "does not have cash";
}
let sentence = "My wallet is " + wallet.color + " and " + money;
return sentence;

}

相关问题