ijavascript函数调用作为三元运算符中的条件奇怪的行为

问题描述

我不知道出了什么问题..

const toggleKls = ()=> isKls() ? ls.setItem(kls,"false") : ls.setItem(kls,"true");

toggleKls() 无法正常工作, 我什至尝试切换 exprIfTrueexprIfFalse 的位置,但 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,"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"}`);
        },false);

//>for development
//>bindings

控制台输出:

const ls = window.localStorage;
const kls = "keyListenSwitch";
const isKls = ()=> ls.getItem(kls);
const toggleKls = ()=> isKls() ? 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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)