代码之家  ›  专栏  ›  技术社区  ›  Zachary Scott

JQuery$.extend的工作方式与我预期的不同:如何正确地编写代码?

  •  1
  • Zachary Scott  · 技术社区  · 14 年前

    Here 是JQuery扩展页。

    var a = [];
    a.push({ "id": 1, "text": "one" });
    a.push({ "id": 2, "text": "two" });
    a.push({ "id": 3, "text": "three" });
    var b = [];
    b.push({"id":3 , "selected":true});
    var c = [];
    $.extend(c,a,b);
    

    我希望得到的结果数组包括:

    { "id": 1, "text": "one", "selected": false }
    { "id": 2, "text": "two", "selected": false }
    { "id": 3, "text": "three", "selected": true }
    

    但它似乎只是将第一个数组复制到第二个数组的顶部:

    { "id": 3, "text": null, "selected": true }
    { "id": 2, "text": "two" }
    { "id": 3, "text": "three" }
    

    当我们向$.extend()提供两个或多个对象时,所有对象的属性都将添加到目标对象中。

    我做错了什么,否则我该怎么做?

    编辑:执行Jball的建议:

    var a = [];
    a.push({ "id": 1, "text": "one" });
    a.push({ "id": 2, "text": "two" });
    a.push({ "id": 3, "text": "three" });
    var b = [];
    b.push({ "id": 3, "selected": true });
    var c = [];
    for (var index = 0; index < a.length; index++) {
       var tempresult = {};
       var tempb = b.filter(
          function (ele, idx, collection) {
             return (collection[idx].id == index + 1);
          });
       if (tempb.length == 0)
          tempb = [{ "id": index + 1, "selected": false }];
       $.extend(tempresult, a[index], tempb[0]);
       c.push(tempresult);
    } 
    

    生产:

    [{"id":1, "selected":false, "text": "one"},
     {"id":2, "selected":false, "text": "two"},
     {"id":3, "selected":true,  "text": "three"}]
    

    这就是答案。现在我想知道是否可以清理一下。

    1 回复  |  直到 14 年前
        1
  •  1
  •   jball    14 年前

    我不确定你是否注意到了,但是 $.extend()

    似乎需要创建一个函数来遍历数组,然后调用 $.extend() 匹配元素以获得所需的结果。您必须决定是否要添加或忽略第二个数组中的不匹配元素。

    问题是jQuery不知道数组中的哪些元素匹配,所以按索引匹配它们,尽管我不确定第一个项的结果为什么 "text": "three" "text": "one" ,除非它在执行 $.extend()