如何javascript if(变量条件[object String])

时间:2017-09-21 02:30:28

标签: javascript variables if-statement conditional-statements

// i want condition using Object String.(Sorry, English little)

'EX)'

var info1 = [
   {orderNum : 001 , state : use , check : O }
   {orderNum : 002 , state : use , check : 1}
   {orderNum : 003 , state : disuse , check : 0}
];
var info2 = [
   {orderNum : 001 , state : use , check : O }
   {orderNum : 002 , state : use , check : 1}
   {orderNum : 003 , state : use , check : 0}
   {orderNum : 004 , state : disuse , check : 0}

];

 var condition = '( info1[i].'+inputText+' == info2[j].'+inputText')';

 console.log(condition)

***result**** ==> (info1[i].orderNum == info1[j].orderNum) && (info1[i].state == info1[j].state);

--------------------------------------------------------------------------------

var equalInfo1 = [];
var equalInfo2 = [];
var differInfo1 = [];
var differInfo2 = [];

for(var i=0: i < info1.length; i++{
 for(var j=0; j< info2.length; j++{

   if(condition){ 
  //  condition =>
  // (info1[i].orderNum == info1[j].orderNum) && (info1[i].state == 
  //  info1[j].state)

     equalInfo1.push(info1[i]);
     equalInfo2.push(info2[j]
   }else{
      differInfo1.push[info1[i];
      equalInfo2.push(info2[j];
   }
 }
}

equalInfo1 => [{orderNum : 1 ...}, {orderNum : 2 ...}]
equalInfo2 => [{orderNum : 1 ...}, {orderNum : 2 ...}]
differInfo1 => [{orderNum : 3 ...}]
differInfo2 => [{orderNum : 4 ...}]

//`i want condition using Object String.(Sorry, English little)`

// but, now logic ==> [variable condition = object String.....] = [Incorrect results] // but, now logic ==> [variable condition = object String.....] = [Incorrect results]

i want

if(variable condition) {

}else{

}

// but, now logic ==> [variable condition = object String.....] = [Incorrect results]

//谢谢。

1 个答案:

答案 0 :(得分:0)

好的,我打算在这个问题上采取行动。我在这里做了很多假设,但我认为你的问题源于尝试使用变量访问对象。

您的物体形状不正确。从0开始的OrderNum值可能不是您想要的,因为JavaScript会将以0开头的数字视为基数8 - 我将它们转换为字符串。同样state值也需要是字符串,我在每个对象后添加逗号以使其有效。

您可以使用info1运算符使用字符串变量来访问info2[ ]的值

var info1 = [
   {orderNum : "001" , state : "use" , check : 0 },
   {orderNum : "002" , state : "use" , check : 1},
   {orderNum : "003" , state : "disuse" , check : 0}
];

var info2 = [
   {orderNum : "001" , state : "use" , check : 0 },
   {orderNum : "002" , state : "use" , check : 1},
   {orderNum : "003" , state : "use" , check : 0},
   {orderNum : "004" , state : "disuse" , check : 0}
];

var orderNum = "orderNum";
var state = "state";

var info1OrderNum = info1[0][orderNum];
var info2OrderNum = info2[0][orderNum];

var info1State = info1[0][state];
var info2State = info2[0][state];

if(info1OrderNum === info2OrderNum && info1State === info2State){
  console.log("we match!");
}
else{
  console.log("we DO NOT match");
}