【发布时间】:2021-03-29 23:11:52
【问题描述】:
我不知道出了什么问题..
const toggleKls = ()=> isKls() ? ls.setItem(kls, "false") : ls.setItem(kls, "true");
toggleKls() 无法按预期工作,
我什至尝试切换 exprIfTrue 和 exprIfFalse 的位置,但 window.localStorage.getItem(kls) 保持不变,与启动时一样
isKls() 也不起作用,
由于某种原因,它总是评估为true..
当我像这样测试这个表达式时
testo = (r)=>r
testo(true) ? false : true
//false
testo(false) ? false : true
//true
它工作得很好,看起来我在下面做同样的事情,但显然不是,我不明白为什么..
//<FOR DEVELOPMENT
const ls = window.localStorage;
const kls = "keyListenSwitch";
const isKls = ()=> ls.getItem(kls);
console.warn(`kls: ${isKls()} test: ${ls.getItem("test")} kls by hand: ${window.localStorage.getItem(kls)}`)
const toggleKls = ()=> isKls() ? ls.setItem(kls, "false") : ls.setItem(kls, "true");
//get any key if switch is on
document.body.addEventListener(
'keydown',
gHandler(
e=> isKls(),
e=> console.log(`event: ctrl:${e.ctrlKey} alt:${e.altKey} shift:${e.shiftKey} key:${e.keyCode}\nkls: ${isKls()}`),
500),
false);
//toggle switch to get any key
document.body.addEventListener(
'keydown',
gHandler(
e=> e.ctrlKey && e.altKey && e.keyCode == 76,//l
()=>{
toggleKls();
console.warn(`TOGGLE Dev:\nListen To Any Key Switch is: ${ isKls() ? "ON" : "OFF"}`);
},
500),
false);
//>for development
//>bindings
控制台输出:
const ls = window.localStorage;
const kls = "keyListenSwitch";
const isKls = ()=> ls.getItem(kls);
const toggleKls = ()=> isKls() ? ls.setItem(kls, "false") : ls.setItem(kls, "true");
isKls()
"false"
//it's false and should toggle to true in that case, but it's not
ls.setItem(kls, true)
undefined
isKls()
"true"
throwByKey.js:334 event: ctrl:true alt:false shift:false key:17
kls: true
throwByKey.js:334 event: ctrl:true alt:true shift:false key:18
kls: true
throwByKey.js:345 TOGGLE Dev:
Listen To Any Key Switch is: ON
(anonymous) @ throwByKey.js:345
(anonymous) @ throwByKey.js:260
throwByKey.js:334 event: ctrl:false alt:true shift:false key:18
kls: false
throwByKey.js:345 TOGGLE Dev:
Listen To Any Key Switch is: ON
(anonymous) @ throwByKey.js:345
(anonymous) @ throwByKey.js:260
throwByKey.js:334 event: ctrl:true alt:true shift:false key:76
kls: false
throwByKey.js:345 TOGGLE Dev:
Listen To Any Key Switch is: ON
(anonymous) @ throwByKey.js:345
(anonymous) @ throwByKey.js:260
throwByKey.js:334 event: ctrl:true alt:false shift:false key:17
kls: false
throwByKey.js:334 event: ctrl:false alt:true shift:false key:18
kls: false
这个函数实际上是在其他任何东西之上声明的,但我把它放在这里只是为了更清楚
//TOOLS
function gHandler (ruler,action,cd){//cool down
let lcd = 0;
let iscd = ()=>{
let t = new Date().getTime();
let tmp = t - lcd;
return lcd = t, tmp >= cd}
return function (e) {
if (ruler(e) && iscd()) {
action(e);
}
}
}
//tools
【问题讨论】:
-
toggleKls() 无法按预期工作, 预期的行为是什么?究竟出了什么问题?
-
请尝试将其缩减为可运行的minimal reproducible example,以证明您的问题
-
也许问题在于您不知道所有函数调用都会执行,而不管条件结果如何。函数首先运行,然后使用这些函数调用的返回值执行条件。
标签: javascript function call operator-keyword ternary