在javascript中是否有明确的方法来做AND NOT条件列表?
Is there any clear way to do a list of AND NOT conditions in javascript?
现在我有一个json对象,示例如下:
{
"a1": "xxx",
"a2": "xxx",
"a3": "xxx",
"b": "xxx",
"c": "xxx",
"d": "xxx",
"e": "xxx",
"f": "xxx"
}
其中a1,a2,a3不总是具有相同的键
(它可以将密钥名称更改为b1,b2,b3或任何其他密钥名称等)
因此,当我想获得这些键的值时,我将在for循环中添加以下条件:
if (key!="b" && key!="c" && key!="d" && key!="e" && key!="f") {}
但是我想有一个明确的方法来实现这个条件。
有更好的解决办法吗?
对于这样的多个条件,我喜欢使用数组并检查值是否在该数组中。稍微好一点。
var key = 'a1';
var key2 = 'b';
if (['b', 'c', 'd', 'e', 'f'].indexOf(key) === -1) {
console.log(key);
}
if (['b', 'c', 'd', 'e', 'f'].indexOf(key2) === -1) {
console.log(key2);
}
var list = {
"a1": "xxx",
"a2": "xxx",
"a3": "xxx",
"b": "xxx",
"c": "xxx",
"d": "xxx",
"e": "xxx",
"f": "xxx"
};
var key;
for (key in list) {
if (['b', 'c', 'd', 'e', 'f'].indexOf(key) === -1) {
console.log('Key not in array', key);
} else {
console.log('Key in array', key);
}
};
您可以使用一个对象作为不需要的键的黑名单。
var data = { a1: "xxx", a2: "xxx", a3: "xxx", b: "xxx", c: "xxx", d: "xxx", e: "xxx", f: "xxx" },
blacklisted = { b: true, c: true, d: true, e: true, f: true };
Object.keys(data).forEach(function(key) {
if (!blacklisted[key]) {
console.log(key)
}
});
如果我是对的,你有一些值,你称它为键。你想遍历所有对象属性并检查每个属性是否都持有那个值吗?
这很简单,你需要使用for..in循环并将key与对象的每个属性进行比较,如果其中一个不同,则以false退出。
你没有指定当你得到空对象时会发生什么?因为我不知道上下文,我假设函数应该对空对象返回false(因此在底部检查)。
将其放入代码:
var key = "xxx";
var keys = {
"a1": "xxx",
"a2": "xxx",
"a3": "xxx",
"b": "xxx",
"c": "xxx",
"d": "xxx",
"e": "xxx",
"f": "xxx"
};
var checkKeys = function(objectWithKeys, key) {
var numberOfProperties = 0;
for (prop in objectWithKeys) {
if (objectWithKeys.hasOwnProperty(prop)) {
numberOfProperties++;
if (objectWithKeys[prop] !== key) return false;
}
}
if (numberOfProperties !== 0) return true;
else return false;
}
我假设你是JS新手,我将解释解决方案中的两个关键部分:
for (property in object)
是功能标准的变体。以这种方式迭代对象属性是最佳实践。
if (objectWithKeys.hasOwnProperty(prop))
是非常重要的检查。默认情况下,当你请求property(如果对象没有)时,它会查找原型链。对象。hasOwnProperty确保你在迭代中从for..获得的属性是在该对象中定义的,而不是你的对象继承的某个对象。
相关文章:
- jQuery is not loaded
- AngularJS JSON not arriving php
- $rootScope not working
- reactRedux is not defined
- Selenium WebDriver and JavaScript change
- jQuery document.ready not working
- Javascript and Css: Height does not change
- :not and :first in jquery
- "callback is not the function" and function.apply(
- Devil of a time with jQuery delegate and .not
- regex匹配除AND、OR和NOT之外的所有单词
- OOP jQuery Plugin elem undefined in one place and not in oth
- ng-repeat and json for child pages not showing in li's
- Systemjs and tsc setup - *.ts.js 404 (Not Found) Error
- Not working in Mozilla firefox and works fine in chrome $(
- $.ajax() and "Uncaught ReferenceError: data is not defi
- 在javascript中是否有明确的方法来做AND NOT条件列表?
- JavaScript RegExp for NOT foo AND NOT bar AND NOT baz
- javascript: get date and time of India (Not of personal comp
- 如何将IF条件与AND条件和NOT操作符在javascript