比较数组中的值失败 [英] Comparing values in Array fails

查看:129
本文介绍了比较数组中的值失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时比较数组中的两个字符串失败。失败偶尔只发生在循环 if 。下面的示例代码代表实现该问题。

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];
  }
}

searchTable strings ,并且所有的值都不相似。

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

尽管 [n-1] [n] 。激活 alert()显示正确的比较结果,但如果全部通过。看起来像中的比较,如果通过引用完成,而不是值。这怎么可能?这是JavaScript解释器中的错误还是什么?

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?

操作可以通过添加 valueOf() -methods到比较表达式中的两个成员。我已经崩溃这个失败的whithin循环如果只。有时需要很长时间才能找出为什么代码不起作用。

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.

推荐答案

与数组中的实际数据相关。我怀疑我们不能更具体地帮助不了解数据是什么。

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.

如果在前面插入 valueOf(),它可以正常工作, valueOf()与直接!= 不同,并将两个值输出到调试控制台或打入调试器所以你可以检查什么值是导致问题。换句话说,编写捕获问题条件并允许您检查它的代码。

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.

这篇关于比较数组中的值失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆