var obj = { key: undefined };console.log(obj["key"] !== undefined); // false, but the key exists!
你应该使用in运算符:
var obj = { key: undefined };console.log("key" in obj); // true, regardless of the actual value
如果要检查键是否不存在,请记住使用括号:
var obj = { not_key: undefined };console.log(!("key" in obj)); // true if "key" doesn't exist in objectconsole.log(!"key" in obj); // Do not do this! It is equivalent to "false in obj"
或者,如果您想特别测试对象实例的属性(而不是继承的属性),请使用hasOwnProperty:
var obj = { key: undefined };console.log(obj.hasOwnProperty("key")); // true
var a = {1: null};console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.: the value is defined.console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].
var obj = {foo: 'one', bar: 'two'};
function isKeyInObject(obj, key) {var res = Object.keys(obj).some(v => v == key);console.log(res);}
isKeyInObject(obj, 'foo');isKeyInObject(obj, 'something');
单行示例。
console.log(Object.keys({foo: 'one', bar: 'two'}).some(v => v == 'foo'));
This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.
const object1 = {a: 'something',b: 'something',c: 'something'};
const key = 's';
// Object.keys(object1) will return array of the object keys ['a', 'b', 'c']
Object.keys(object1).indexOf(key) === -1 ? 'the key is not there' : 'yep the key is exist';
let arr = ["a","b","c"]; // we have indexes: 0,1,2delete arr[1]; // set 'empty' at index 1arr.pop(); // remove last item
console.log(0 in arr, arr[0]);console.log(1 in arr, arr[1]);console.log(2 in arr, arr[2]);
const hasKey = 'FinancialRiskIntent' in data.meta.prediction.intents;
if(hasKey) {console.log('The key exists.');}else {console.log('The key does not exist.');}
let person = {hasOwnProperty: function() {return false;},age: 35};
if (Object.hasOwn(person, 'age')) {console.log(person.age); // true - the remplementation of hasOwnProperty() did not affect the Object}
let person = Object.create(null);person.age = 35;if (Object.hasOwn(person, 'age')) {console.log(person.age); // true - works regardless of how the object was created}
// badconsole.log(object.hasOwnProperty(key));
// goodconsole.log(Object.prototype.hasOwnProperty.call(object, key));
// bestconst has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.console.log(has.call(object, key));/* or */import has from 'has'; // https://www.npmjs.com/package/hasconsole.log(has(object, key));