问题描述
我需要将 ??
C#运算符应用于JavaScript,我不知道如何操作。
在C#中考虑这个:
I have a requirement to apply the ??
C# operator to JavaScript and I don't know how.Consider this in C#:
int i?=null;
int j=i ?? 10;//j is now 10
现在我在JavaScript中设置了这个:
Now I have this set up in JavaScript:
var options={
filters:{
firstName:'abc'
}
};
var filter=options.filters[0]||'';//should get 'abc' here, it doesn't happen
var filter2=options.filters[1]||'';//should get empty string here, because there is only one filter
我该如何正确地做到这一点?
How do I do it correctly?
谢谢。
编辑:我发现问题的一半:我不能使用'索引器'对象的表示法( my_object [0]
)。有没有办法绕过它? (我事先不知道过滤器属性的名称,也不想迭代它们。)
I spotted half of the problem: I can't use the 'indexer' notation to objects (my_object[0]
). Is there a way to bypass it? (I don't know the names of the filters properties beforehand and don't want to iterate over them).
推荐答案
这里是等价的JavaScript:
Here’s the JavaScript equivalent:
var i = null;
var j = i || 10; //j is now 10
请注意不返回布尔值但是返回第一个值可以转换为 true 。
另外使用一个对象数组而不是一个对象:
Additionally use an array of objects instead of one single object:
var options = {
filters: [
{
name: 'firstName',
value: 'abc'
}
]
};
var filter = options.filters[0] || ''; // is {name:'firstName', value:'abc'}
var filter2 = options.filters[1] || ''; // is ''
可以通过索引访问。
这篇关于如果在JavaScript中为null或未定义,则替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!