วิธีที่ดีในการเข้าถึงจากชื่อสตริงแบบไดนามิกที่มีวัตถุ (เช่น object.subobject.property)
function ReadValue(varname)
{
var v=varname.split(".");
var o=window;
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
return o[v[v.length-1]];
}
function AssignValue(varname,value)
{
var v=varname.split(".");
var o=window;
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
o[v[v.length-1]]=value;
}
ตัวอย่าง:
ReadValue("object.subobject.property");
WriteValue("object.subobject.property",5);
eval ใช้ได้กับค่าการอ่าน แต่ค่าการเขียนนั้นค่อนข้างยาก
เวอร์ชันขั้นสูงเพิ่มเติม (สร้างคลาสย่อยหากไม่มีอยู่และอนุญาตให้วัตถุแทนตัวแปรกลาง)
function ReadValue(varname,o=window)
{
if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
return undefined;
var v=varname.split(".");
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
if(typeof(o[v[v.length-1]])==="undefined")
return undefined;
else
return o[v[v.length-1]];
}
function AssignValue(varname,value,o=window)
{
if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
return;
var v=varname.split(".");
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
o[v[v.length-1]]=value;
}
ตัวอย่าง:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
นี่เป็นสิ่งเดียวกันกับที่ o.object.subobject.property