الرسالة
TypeError: Unable to get property {x} of undefined or null reference (Edge) TypeError: "x" is (not) "y" (Firefox) Examples: TypeError: "x" is undefined TypeError: "x" is null TypeError: "undefined" is not an object TypeError: "x" is not an object or null TypeError: "x" is not a symbol
نوع الخطأ
ماذا حصل؟
خطأ غير متوقع، يحدث كثيرا مع undefined
أو قيم null
.
أيضا في بعض الوضائف مثل Object.create()
أو Symbol.keyFor()
, تحتاج تقديد أنواع محددة.
أمثلة
حالات غير صحيحة
// undefined and null cases on which the substring method won't work
var foo = undefined;
foo.substring(1); // TypeError: foo is undefined
var foo = null;
foo.substring(1); // TypeError: foo is null
// Certain methods might require a specific type
var foo = {}
Symbol.keyFor(foo); // TypeError: foo is not a symbol
var foo = 'bar'
Object.create(foo); // TypeError: "foo" is not an object or null
حل المشكلة
لإصلاح مؤشر null إلى قيم undefined
أو null
، يمكنك استخدام عامل التشغيل typeof ، على سبيل المثال.
if (typeof foo !== 'undefined') {
// الآن نعلم أن القيمة المدخلة غير محددة، نستطيع القيام بأي إجراء بدون خطأ.
}