2

我有以下代码:

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');
    });
});

当我运行这个时,只会弹出“case 1”。从逻辑上讲,传递属性应该是正确的,所以我猜这是一些 JavaScript 字符串语法问题,或者 jQuery 范围的事情搞砸了。任何建议表示赞赏。

4

4 回答 4

2

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

jQuery.each使用apply传递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返回组成它的原始字符串,如果两个原始字符串的字符相等,则它们相等。

于 2012-06-05T16:47:23.870 回答
1

Try like below,

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');
    });
 });

Note: I assume the above is just a pseudo code. We can help better if you let us know what you are trying to do.

DEMO

于 2012-06-05T16:10:03.460 回答
0
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');
    });
});

示例锻炼

于 2012-06-05T16:06:07.767 回答
0

尝试这个:

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');
   });
});​

这是演示

于 2012-06-05T16:24:36.480 回答