j查询字符串比较变量

jquery string comparison variable

本文关键字:变量 比较 字符串 查询      更新时间:2023-09-26

我有以下代码:

arr = ["abc", "def", "ghi", "jkl"]
arr2 = ["abc", "def", "ghi", "jkl"]
$(arr).each(function(){
    thiselem = this;
    $(arr2).each(function(){
        if(thiselem == "abc" && this == "abc")
            alert("case 1");
        if(thiselem == this)
            alert('case 2');
    });
});

当我运行这个时,只会弹出"案例 1"。从逻辑上讲,传递属性的这个陈述应该是真的,所以我猜这是一些 JavaScript 字符串语法问题,或者 jQuery 范围的事情搞砸了。任何建议不胜感激。

其他海报提出了解决方法,我将尝试回答为什么您的原始代码不起作用的问题。答案相当不平凡,揭示了一些众所周知的JavaScript陷阱。

jQuery.each 用法适用于将this传递给其回调。当 apply 的参数是一个原始值时,如字符串,它将被"装箱",即转换为对象(特别是String对象):

console.log(typeof("cat"))  // string
logger = function() { console.log(typeof(this)) }
logger.apply("cat")  // object

现在考虑以下几点:

a = ["abc"]
b = ["abc"]
$(a).each(function() {
   var that = this
   $(b).each(function() {
       console.log(this == that) // false!
   })
})

尽管 a[0] 和 b[0] "明显"相等,但 == 运算符返回 false,因为两者都是对象,并且两个对象变量只有在物理上是相同的对象时才相等。另一方面,这按预期工作:

a = ["abc"]
b = ["abc"]
$(a).each(function() {
     console.log(this == "abc") // true
     console.log(this == b[0]) // true
})

当 JS 将对象与字符串进行比较时,使用 toString 将对象转换为字符串原语。由于 this 是一个 String 对象,因此它的toString返回它所由的基元字符串,如果两个基元字符串的字符相等,则它们相等。

尝试如下,

var arr = ["abc", "def", "ghi", "jkl"]
var arr2 = ["abc", "def", "ghi", "jkl"]
$(arr).each(function(idx, el){
    $(arr2).each(function(idx, iEl){
        if(el == "abc" && iEl == "abc")
            alert("case 1");       
        if(el == iEl)
            alert('case 2');
    });
 });

注意:我假设以上只是一个伪代码。如果您让我们知道您要做什么,我们可以提供更好的帮助。

演示

arr = ["abc", "def", "ghi", "jkl"]
arr2 = ["abc", "def", "ghi", "jkl"]
$(arr).each(function(index, val1) {
    $(arr2).each(function(i, val2) {
        if (val1 == "abc" && val2 == "abc") alert("case 1");
        if (val1 == val2) alert('case 2');
    });
});

锻炼示例

试试这个:

var arr = ["abc", "def", "ghi", "jkl"]
var arr2 = ["abc", "def", "ghi", "jkl"]
jQuery.each(arr,function(key1, val1){
  jQuery.each(arr2,function(key2, val2 ){
    if(val1 == "abc" && val2 == "abc")
        alert("case 1");       
    if(val1 == val2)
        alert('case 2');
   });
});​

这是演示