我想创建一个有条件添加成员的对象.简单的方法是:
var a = {};
if (someCondition)
a.b = 5;
Run Code Online (Sandbox Code Playgroud)
现在,我想写一个更惯用的代码.我在尝试:
a = {
b: (someCondition? 5 : undefined)
};
Run Code Online (Sandbox Code Playgroud)
但现在,b是a其价值的成员undefined.这不是理想的结果.
有方便的解决方案吗?
更新
我寻求一个可以处理几个成员的一般情况的解决方案.
a = {
b: (conditionB? 5 : undefined),
c: (conditionC? 5 : undefined),
d: (conditionD? 5 : undefined),
e: (conditionE? 5 : undefined),
f: (conditionF? 5 : undefined),
g: (conditionG? 5 : undefined),
};
Run Code Online (Sandbox Code Playgroud) JavaScript中的值是什么'falsey',这意味着它们在表达式中评估为false if(value),value ?并且!value?
关于Stack Overflow上的falsey值的目的已有一些讨论,但没有详尽的完整答案列出所有的falsey值.
我在MDN JavaScript Reference上找不到任何完整列表,我很惊讶地发现在JavaScript中查找完整,权威的虚假值列表时的最佳结果是博客文章,其中一些有明显的遗漏(例如,NaN),并且没有一个像Stack Overflow这样的格式,可以添加评论或替代答案来指出怪癖,惊喜,遗漏,错误或警告.因此,制作一个似乎是有意义的.
有人可以使用下面的示例数据解释JavaScript Truthy和Falsy.我已阅读其他主题但仍感到困惑.
var a = 0;
var a = 10 == 5;
var a = 1;
var a = -1;
Run Code Online (Sandbox Code Playgroud)
根据我的理解,我相信这var a = 1;是唯一的真理,其余的都是假的 - 这是正确的吗?
all is not a built-in function or keyword, but why can I not call a function if it is named all?
There is no error message in the debug console, and the function works if I rename it to all2.
Here is the code: tested in chrome and IE10
<!DOCTYPE html>
<head>
</head>
<body>
<script>
function all()
{
alert(1);
}
function all2()
{
alert(2);
}
</script>
<input type="button" value="all1" onclick="all()">
<input type="button" value="all2" onclick="all2()">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我正在对JavaScript的typeof运算符进行一些研究,并偶然发现了以下奇怪之处:
例外
所有当前浏览器都公开
document.all类型为Undefined 的非标准主机对象.Run Code Online (Sandbox Code Playgroud)typeof document.all === 'undefined';虽然规范允许非标准外来对象的自定义类型标记,但它要求那些类型标记与预定义标记不同.
document.all具有类型标签的情况'undefined'必须归类为违反规则的例外情况.
(来源)
我在浏览器中设置了以下内容来测试它:
console.log("typeof: " + typeof document.all);
console.log("toString: " + document.all);
Run Code Online (Sandbox Code Playgroud)
它产生了:
typeof: undefined
toString: [object HTMLAllCollection]
Run Code Online (Sandbox Code Playgroud)
那么为什么会document.all这样呢?既然document.all是一个对象(在我的浏览器中定义),不应该typeof返回"object",不是"undefined"吗?