首页 > 解决方案 > 如何在javascript中的语句之前理解下划线

问题描述

_此示例代码中的含义是什么:

if (_(abc.content).has("abc")){
    console.log("abc found");
}

很多人说“_”表示私有成员,但是如果abcorcontent是私有成员,我们不应该使用_abc.contentorabc._content吗?

谢谢

标签: javascript

解决方案


要使其有效,_必须引用一个函数。也许脚本正在使用underscore,在这种情况下,如果对象的为,则_(abc.content).has("abc")返回布尔值,否则:trueabc.contentabcfalse

const abc = { content: { key1: 'foo', abc: 'bar' } };

if (_(abc.content).has("abc")){
    console.log("abc found");
}

console.log(_(abc.content).has("keyThatDoesNotExist"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

它可能与私有属性无关,因为_它是一个独立的函数。

使用的库也可能是 lodash:

const abc = { content: { key1: 'foo', abc: 'bar' } };

if (_(abc.content).has("abc")){
    console.log("abc found");
}

console.log(_(abc.content).has("keyThatDoesNotExist"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>

但可以肯定的是,您必须检查它_console.log或者查看它的定义位置,以获得一些想法。


推荐阅读