如何检查名为id的变量属性

How can I check if variable property named id?

本文关键字:id 变量 属性 何检查 检查      更新时间:2023-09-26

我有一个名为t的变量。

有时这个变量等于某个对象:

var t = {id:2 Name:"Mike" };

有时这个变量可能只包含字符串。像这样:

 var t = "someString";

在某个时刻,我需要检查变量是否是对象,以及它是否包含名为id的属性。

如何检查变量是否为对象并包含名为id的属性?

您可以使用&&(和)运算符

if (t && t.id && td.id === "blah")

或更短:

if (t && t.id === "blah")

使用typeofhasOwnProperty:

if(typeof t == 'object' && t.hasOwnProperty('id')) {
     //your code for using t.id
}

您可以使用toString.call(value) === '[object Object]'toString.call(value) === '[object String]' 检查变量

var t = {
  id: 2,
  Name: "Mike"
};
function isObject(value, property) {
  return value !== null && toString.call(value) === '[object Object]' && value.hasOwnProperty(property);
}
function isString(value) {
  return value !== null && toString.call(value) === '[object String]';
}
document.write("isObject : " + isObject(t, 'id') + " | " + "isString : " + isString(t) + "<br>");
var t = "blabla";
document.write("isObject : " + isObject(t, 'id') + " | " + "isString : " + isString(t));