Comparing values in Array fails

旧街凉风 提交于 2019-12-11 15:36:02

问题


Sometimes comparing two strings within arrays fails. Failing occurs occasionally only in looped ifs. Example code below stands for implementing the problem.

searchTable.sort();
for(n=1;n<searchTable.length;n++){
  // alert(searchTable[n-1]!=searchTable[n]);
  if(searchTable[n-1]!=searchTable[n]){
    idx++;
    memTable[idx]=searchTable[n];
  }
}

Values in the searchTable are strings for sure, and all values are not similar either.

In loop, all values are set in memTable[idx], despite of the similar values in [n-1] and [n]. Activated alert() shows the right comparison result, but if passes all through. Looks like the comparison in if is done by reference, not by value. How is this possible? Is this a bug in the JavaScript interpreter or what?

Action can be corrected by adding valueOf()-methods to both members in comparison expression. I've crashed this failier whithin looped ifs only. Sometimes it takes a long time to figure out why the code won't work.


回答1:


You seem to have concluded that the problem is related to the actual data in the arrays. I suspect we can't help more specifically without seeing what that data is.

If putting valueOf() in front makes it work, then you can code a check for when the comparison with valueOf() is different than just straight != and output the two values to the debug console or break into the debugger so you can inspect what values are causing the problem. In other words, write code that catches the problem condition and allows you to inspect it.




回答2:


Looks like you want to remove double values from an Array. Try using:

var tmpObj = {}, resultArr = [];
for(n=1;n<searchTable.length;n++){
  if (searchTable[n] in tmpObj){
    continue;
  }
  tmpObj[searchTable[n]] = true;
}
for (var l in tmpObj){
 resultArr.push(l);
}

Note: this will not differentiate between Numbers and Strings (so 1 equals '1')



来源:https://stackoverflow.com/questions/9056270/comparing-values-in-array-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!