我有一个线性(或单维)对象,在单个记录中具有 1000 多个属性。我必须遍历超过 10000 条记录。有时,单个记录中的对象可能不包含所需的属性。我想知道通过循环对象的所有属性或通过引用它直接检查对象中的键是否可用来遍历它们的更好策略是什么。请检查以下示例以更好地理解这一点。
让我们考虑一个示例场景:
var a = {
"x": 1,
"y": 2,
"z": 3,
"t": 4
}; //linear object
var flagA = false;
var b = {
"x": 10,
"y": 11,
"z": 12
}; //linear object
var flagB = false;
//now I have to check the value of "t" in both objects.
//----------------------------------By use of looping-------------------------------//
for (var i in a) {
if (i == "t") {
flagA = true;
break;
}
}
for (var i in b) {
if (i == "t") {
flagB = true;
break;
}
}
//for object a
if (flagA) console.log("value found in object a for t:", a.t);
else console.log("value not found for t in object a");
//for object b
if (flagB) console.log("value found in object b for t:", a.t);
else console.log("value not found for t in object b");
//--------------------------------------------------------------------------------------//
console.log("\nANOTHER METHOD\n");
//-----------------------------------By use of Key-------------------------------------//
//for object a
if (a["t"]) console.log("value found in object a for t:", a["t"]);
else console.log("value not found for t in object a");
//for object b
if (b["t"]) console.log("value found in object b for t:", b["t"]);
else console.log("value not found for t in object b");
//--------------------------------------------------------------------------------------//
我应该使用哪一种方法,为什么?