如何检查对象在JavaScript中是否具有特定属性?
如何检查对象在JavaScript中是否具有特定属性 考虑:如何检查对象在JavaScript中是否具有特定属性?,javascript,Javascript,如何检查对象在JavaScript中是否具有特定属性 考虑: x = {'key': 1}; if ( x.hasOwnProperty('key') ) { //Do this } 这是最好的方法吗?是的:)我想你也可以做Object.prototype.hasOwnProperty.call(x,'key'),如果x有一个名为hasOwnProperty的属性,这个方法也应该有效:) 但这是对自身属性的测试。如果你想检查它是否有一个可能也存在的属性,你可以使用typeof x.fo
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?是的:)我想你也可以做Object.prototype.hasOwnProperty.call(x,'key')
,如果x
有一个名为hasOwnProperty
的属性,这个方法也应该有效:)
但这是对自身属性的测试。如果你想检查它是否有一个可能也存在的属性,你可以使用typeof x.foo!='未定义的“
if (x.key !== undefined)
似乎已经,但是:
一个更安全但速度较慢的解决方案是:
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};
好的,看起来我的答案是正确的,除非您不想要继承属性:
if (x.hasOwnProperty('key'))
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)
以下是包括继承属性的其他一些选项:
if (x.hasOwnProperty('key'))
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)
因为
if (x.key)
如果
x.key
解析为false
(例如,x.key=”“
),则失败。注意:由于严格的模式,hasOwnProperty
,以下内容现在已基本过时。正确的解决方案是使用严格模式,并使用obj.hasOwnProperty
检查属性的存在。这个答案早于这两件事,至少也得到了广泛的实施(是的,就是这么古老)。将以下内容作为历史记录
请记住,如果您没有使用严格模式,则
未定义的
在JavaScript中(不幸地)不是保留字。因此,有人(显然是其他人)可能会有重新定义它的伟大想法,破坏您的代码
因此,更稳健的方法如下:
if (typeof(x.attribute) !== 'undefined')
另一方面,这种方法更加冗长,速度也较慢-/
一种常见的替代方法是确保undefined
实际上是未定义的,例如,将代码放入一个函数,该函数接受一个名为undefined
的附加参数,该参数没有传递值。为了确保它没有传递值,您可以自己立即调用它,例如:
(function (undefined) {
… your code …
if (x.attribute !== undefined)
… mode code …
})();
我真的被给出的答案弄糊涂了——大多数答案都是完全错误的。当然,您可以拥有具有未定义、null或false值的对象属性。因此,简单地将属性检查减少到[property]的
类型,或者更糟糕的是,x.key
将给您带来完全误导性的结果
这取决于你在找什么。如果您想知道一个对象是否实际包含属性(并且它不是来自原型链上的某个位置),那么object.hasOwnProperty
是一个不错的选择。所有现代浏览器都支持它。(旧版本的Safari-2.0.1和更旧版本中缺少了它,但这些版本的浏览器很少再使用了。)
如果您要查找的是某个对象上是否有可编辑的属性(当您迭代该对象的属性时,它会出现),则执行:prop in object
将为您提供所需的效果
由于使用hasOwnProperty
可能是您想要的,并且考虑到您可能需要回退方法,我向您提供以下解决方案:
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
以上是一个工作的、跨浏览器的解决方案,用于解决hasOwnProperty
,但有一个警告:它无法区分原型和实例上存在相同属性的情况-它只是假设它来自原型。根据您的情况,您可以将其改为更宽松或更严格,但至少这会更有帮助。让我们在这里排除一些混淆。首先,假设hasOwnProperty
已经存在,让我们简化一下;目前使用的绝大多数浏览器都是如此
hasOwnProperty
如果传递给它的属性名称已添加到对象中,则返回true。它完全独立于分配给它的实际值,而实际值可能是未定义的
因此:
var o = {}
o.x = undefined
var a = o.hasOwnProperty('x') // a is true
var b = o.x === undefined // b is also true
var o = {}
var a = o.hasOwnProperty('x') // a is now false
var b = o.x === undefined // b is still true
但是:
var o = {}
o.x = undefined
var a = o.hasOwnProperty('x') // a is true
var b = o.x === undefined // b is also true
var o = {}
var a = o.hasOwnProperty('x') // a is now false
var b = o.x === undefined // b is still true
问题是当原型链中的对象具有值为undefined的属性时会发生什么hasOwnProperty
将为false,因此!==未定义
。但是,for..in
仍将在枚举中列出它
底线是没有跨浏览器的方式(因为InternetExplorer不公开\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
它调用Object.prototype.hasOwnProperty
,但(a)的键入长度较短,并且(b)使用“对hasOwnProperty
的安全引用”(即,即使hasOwnProperty
被覆盖,它也能工作)
具体而言,Lodash将\uhas
定义为:
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty
使用:
var x={
“键”:1
};
如果(x中的“键”){
console.log('has');
}
如果您正在搜索某个属性,则选择“否”。你想要:
if ('prop' in obj) { }
通常,您不应该关心属性是否来自原型或对象
但是,由于您在示例代码中使用了“key”,因此看起来您将对象视为散列,在这种情况下,您的答案是有意义的。所有哈希键都是对象中的属性,您可以避免原型提供的额外属性
非常全面,但我觉得不清楚。特别是在obj中何时使用“'prop'”您可以使用
中的操作符检查对象上是否存在属性:
x = {'key': 1};
alert("key" in x);
您还可以使用for-in
循环遍历对象的所有属性,然后检查特定属性:
for (prop in x) {
if (prop == "key") {
//Do something
}
}
if (typeof x.key == "undefined") {
alert("undefined");
}
您必须考虑此对象属性是否可枚举,因为在<< /Cult>循环中,不可枚举属性不会出现在<代码>中。此外,如果可枚举属性隐藏原型的不可枚举属性,则它将
if (x.key === undefined) {
alert("undefined");
}
x = {'key': 1};
y = 'key';
x[y];
var noInfo = {};
var info = {something: 'data'};
Object.keys(noInfo).length //returns 0 or false
Object.keys(info).length //returns 1 or true
if (prop in object) { // Do something }
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
x = {'key': 1};
Reflect.has( x, 'key'); // returns true
if (obj[x] !== undefined)
if (obj.hasOwnProperty(x))
function hasKey1(k,o) { return (x in obj); }
function hasKey2(k,o) { return (obj[x]); }
function hasKey3(k,o) { return (obj[x] !== undefined); }
function hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }
function hasKey5(k,o) { return (obj.hasOwnProperty(x)); }
if (X in Obj)...
hasKey1 execution time: 4.51 s
hasKey2 execution time: 0.90 s
hasKey3 execution time: 0.76 s
hasKey4 execution time: 0.93 s
hasKey5 execution time: 2.15 s
/**
Gets an argument from array or object.
The possible outcome:
- If the key exists the value is returned.
- If no key exists the default value is returned.
- If no default value is specified an empty string is returned.
@param obj The object or array to be searched.
@param key The name of the property or key.
@param defVal Optional default version of the command-line parameter [default ""]
@return The default value in case of an error else the found parameter.
*/
function getSafeReflectArg( obj, key, defVal) {
"use strict";
var retVal = (typeof defVal === 'undefined' ? "" : defVal);
if ( Reflect.has( obj, key) ) {
return Reflect.get( obj, key);
}
return retVal;
} // getSafeReflectArg
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
// ...
console.log(has.call(object, key));
var isProperty = (objectname.keyname || "") ? true : false;
var obj = {a:1}
console.log('a' in obj) // 1
console.log(obj.hasOwnProperty('a')) // 2
console.log(Boolean(obj.a)) // 3
for(let key of Object.keys(stud)){
console.log(key); // will only log object's Own properties
}
function Student() {
this.name = "nitin";
}
Student.prototype = {
grade: 'A'
}
let stud = new Student();
// for-in approach
for(let key in stud){
if(stud.hasOwnProperty(key)){
console.log(key); // only outputs "name"
}
}
//Object.keys() approach
for(let key of Object.keys(stud)){
console.log(key);
}
const object= {key1: 'data', key2: 'data2'};
Object.keys(object).includes('key1') //returns true
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
Object.keys(myObject).includes('myKey')
myObject.hasOwnProperty('myKey')
typeof myObject.myKey !== 'undefined'