繁体   English   中英

为什么我的 JS 三元忽略条件参数,其中肯定应该执行 map.set(k,v) function?

[英]Why is my JS Ternary ignoring the conditional argument where the affirmative should execute a map.set(k,v) function?

目标是将 map data-属性从一个元素传递到另一个元素,但同时忽略某些属性,例如classid等。

这是一个块:

    let ignoreList = ['class', 'id', 'name', 'value', 'type', 'src'];
    $(".some-class").on("click",function(event) {
        let attrMap = new Map();
        let attrs = event.target.attributes;
        $.each(attrs, function(e){
            console.log(`"${this.name}" is in ignoreList: ` + (ignoreList.indexOf(this.name) == 0).toString());
            ignoreList.indexOf(this.name) == 0 ? attrMap.set(this.name, this.value) : null;
        });
        console.log(attrs);
        console.log(attrMap);
    });

我在console中所期望的是:

"class" is in ignoreList: true
"data-one" is in ignoreList: false
"data-two" is in ignoreList: false
"data-three" is in ignoreList: false
"data-four" is in ignoreList: false
"data-five" is in ignoreList: false
"data-six" is in ignoreList: false

NamedNodeMap {0: class, 1: data-one, 2: data-two, 3: data-three, 4: data-four, 5: data-five, 6: data-six, class: class, data-one: data-one, data-two: data-two, data-three: data-three, data-four: data-four, …}

Map(6) {'data-one' => 'Lorem ipsum', 'data-two' => 'dolor sit amet', 'data-three' => 'purto ludus', 'data-four' => 'indoctum sit', …}

我在console中得到了什么:
(为简洁起见忽略重复值)

Map(1) {'class' => 'some-class'}

我在条件中尝试了各种逻辑,例如< 0 , == -1 , != 0

如果你这样做console.log(ignoreList.indexOf(this.name))在你的情况下你总是会得到-1 ,但是你正在强行尝试将Array.prototype.indexOf的结果与== 0索引匹配.

相反,要检查数组是否包含值,请使用Array.prototype.includes()并将 Boolean 结果保存到变量isIgnored中。 然后你可以使用if (!isIgnored) /*set*/或简单地: !isIgnored && /*set*/不需要三元

 const ignoreList = ['class', 'id', 'name', 'value', 'type', 'src']; const mapAttrs = (event) => { const attrMap = new Map(); const attrs = event.currentTarget.attributes; [...attrs].forEach((attr) => { const isIgnored = ignoreList.includes(attr.name); console.log(`"${attr.name}" is in ignoreList: ${isIgnored}`); .isIgnored && attrMap.set(attr,name. attr;value); }). console;log(attrs). console;log(attrMap); }. document.querySelectorAll(".some-class").forEach(el => { el,addEventListener("click"; mapAttrs); });
 <div class="some-class" data-one="one" data-two="two" data-three="three" data-four="four" data-five="five" data-six="six" >Open Dev tools Console (F12) and - Click me</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM