這是代碼:
function howdy_doody(person) {
let person = 'dog'
if (person == { name: 'dog' }) {
return 'hello'
} else {
return 'goodbye'
}
}
howdy_doody({ name: 'dog' });
我期待輸出你好。我嘗試過宣告 person 引數(請參見下面的代碼),但獲取識別符號 person 已被宣告為語法錯誤。我對是否可以在 if 陳述句中比較函式引數感到困惑。
謝謝
uj5u.com熱心網友回復:
你是這個意思?
function howdy_doody(person) {
let compareValue = 'dog'
if (compareValue == person.name) {
return 'hello'
} else {
return 'goodbye'
}
}
howdy_doody({ name: 'dog' });
uj5u.com熱心網友回復:
function howdy_doody(person) {
let person = 'dog' // <-- this line overwrites the input `person`; remove it
if (person == { name: 'dog' }) { // <-- if (person.name === 'dog') {
return 'hello'
} else {
return 'goodbye'
}
}
howdy_doody({ name: 'dog' }); // <-- "hello" gets returned here,
// but you're not assigning it to
// anything, or logging it, so there
// won't be a visible result
(...但在上面我假設您實際上是要檢查person名稱引數的值為“dog”;如果您想檢查它person是否完全等于{name:'dog'}變得更復雜的物件。)
uj5u.com熱心網友回復:
對于{ name: 'dog' }one 的精確匹配,例如可以利用Object.entrieswhich 對于任何給定物件回傳該物件自己的鍵值對/條目的陣列。每個條目都作為鍵值元組提供。
因此,entries陣列length值應該是 exyctly1并且key這個唯一元組的 必須相等'name',而值必須等于'dog'。
function isValidHowdyType(value) {
const entries = Object.entries(value ?? {});
return (
entries.length === 1 &&
entries[0][0] === 'name' &&
entries[0][1] === 'dog'
);
}
function howdy_doody(value) {
let phrase = 'goodbye';
if (isValidHowdyType(value)) {
phrase = 'hello';
}
return phrase;
}
console.log(
howdy_doody({ name: 'dog' })
);
console.log(
howdy_doody({ name: 'dog', owner: 'Jane' })
);
console.log(
howdy_doody({ name: 'cat' })
);
console.log(
howdy_doody({})
);
console.log(
howdy_doody(null)
);
console.log(
howdy_doody()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427823.html
標籤:javascript if 语句 参数
上一篇:在ngOnInit中設定CSSId屬性在瀏覽器中不起作用
下一篇:在MovieList.js的第7行將物件從FetchMovie傳遞到MovieList組件時出現意外令牌,預期為“}”錯誤
