我正在嘗試創建一個檢查,以查看欄位是否已從占位符值更改。如果沒有,我重新分配原始changed值,因為函式(在我的實際代碼庫中)必須查看多個欄位。
我只是有點困惑為什么:
changed = (locationField.value && locationField.value !== locationField.placeholder) ? true : changed;
如果提交的欄位沒有值,則評估為空字串*。
*在文章末尾輸出
我假設它是 的空值locationField.value,但它不應該分配“真”或改變的值嗎?改變(據我所知)永遠不會也不應該是一個字串。
可能是一個簡單的問題,但我看不到答案。
密碼筆
const locationField = document.querySelector('.location');
const submit = document.querySelector('.submit');
let changed = false;
submit.addEventListener('click', e => {
changed = (locationField.value && locationField.value !== locationField.placeholder) ? true : changed;
console.log(locationField.value, locationField.placeholder, (locationField.value && locationField.value !== locationField.placeholder));
console.log(changed);
// reset
changed = false;
});
<input type="text" placeholder="test" class="location">
<button class="submit">Submit</button>
**編輯:
我得到的結果:
輸入“改變”=>"changed", "test", true
輸入“測驗” =>"test", "test", false
輸入 "" "", "test", "",當我期望"", "test", false
uj5u.com熱心網友回復:
邏輯與 (&&) 從左到右計算運算元,立即回傳它遇到的第一個假運算元的值;如果所有值都為真,則回傳最后一個運算元的值。
(來源:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND )
因此,在您的情況下,如果locationField.value是“”,其評估結果為假值,則邏輯與將回傳的值 locationField.value(這就是它回傳空字串的原因)
uj5u.com熱心網友回復:
如果您首先轉換locationField.value為布林值,無論是 with!!還是 with Boolean(),那么您應該得到預期的結果。
(!!locationField.value && locationField.value !== locationField.placeholder)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/476978.html
標籤:javascript
上一篇:如何在vanillaJS中重寫這個ramda.js代碼
下一篇:如何將陣列元素分組到新的組陣列?
