for循环内部for循环弄乱变量

时间:2017-10-01 11:34:32

标签: javascript arrays javascript-objects

您好我正在尝试按字母顺序重新排列/排序我的projectsDATA变量。但是当我在控制台中运行sort()函数时,我的代码只会弄乱我的变量。例如,如果我的projectsDATA变量是:

var projectsDATA = [B, C, D, A];

如果我用这个变量运行我的代码,输出将是[A,C,C,A],但输出似乎不是“系统的”。

我希望你能理解我的问题。

我已经检查了我的代码中的所有内容,以找出如何解决这个问题,并且我已经找到问题发生在3. for循环中,如下所示:

for(var index2 = 0; index2 < projectsDATAcopy.length; index2 = index2 + 1){
        if (arrayChecked[index] == projectsDATAcopy[index2].title) {
            console.log(arrayChecked[index], projectsDATA[index], projectsDATAcopy[index2]);
            projectsDATA[index] = projectsDATAcopy[index2];
        }
    }

我知道我的代码并不完美,但任何帮助都会受到赞赏:)

var projectsDATA = [
    {
        "href":"/cancerSimulation",
        "theclass":"p5js websites",
        "btnValue": "Cancer Simulator",
        "title": "Aancer Simulation",
        "description": "Cancer Simulation as addition to exam project Cancer Simulation as addition to exam project Cancer Simulation as addition to exam project Cancer Simulation as addition to exam project",
        "date":[2017, "2017",5, "may"]
    },
    {
        "href":"/encryptionProject",
        "theclass":"websites",
        "btnValue": "Facebook Encryption Tool",
        "title": "Bacebook Encryption Tool",
        "description": "Facebook Encryption Tool",
        "date":[2016, "2016",12, "December"]
    },
    {
        "href":"/encryptionProject",
        "theclass":"websites",
        "btnValue": "Facebook Encryption Tool",
        "title": "Dacebook Encryption Tool",
        "description": "Facebook Encryption Tool",
        "date":[2016, "2016",12, "December"]
    }, 
    {
        "href":"/encryptionProject",
        "theclass":"websites",
        "btnValue": "Facebook Encryption Tool",
        "title": "Cacebook Encryption Tool",
        "description": "Facebook Encryption Tool",
        "date":[2016, "2016",12, "December"]
    }
];

var projectsDATAcopy;
console.log(projectsDATA);
var arrayCheck = [];
var arrayChecked;

function sort() {
    projectsDATAcopy = projectsDATA;
    console.log(projectsDATAcopy, projectsDATA);
    var sortValue = document.getElementById("sorting").value;

    if (sortValue == "Alphabetical") {
        for(var index3 = 0; index3 < projectsDATAcopy.length; index3++){
            arrayCheck[index3] = projectsDATAcopy[index3].title;
            console.log(arrayCheck);
        }
        arrayChecked = arrayCheck.sort();
        console.log(arrayChecked);
        console.log(projectsDATAcopy, projectsDATA);

        for(var index = 0; index < arrayChecked.length; index = index +1){
            console.log(arrayChecked[index]);
            for(var index2 = 0; index2 < projectsDATAcopy.length; index2 = index2 + 1){
                if (arrayChecked[index] == projectsDATAcopy[index2].title) {
                    console.log(arrayChecked[index], projectsDATA[index], projectsDATAcopy[index2]);
                    projectsDATA[index] = projectsDATAcopy[index2];
                }
            }
        }
        console.log(projectsDATA);
    }
}

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用Array.prototype.sort

projects.sort((projectX, projectY) => projectX.title.localeCompare(projectY.title));

不幸的是,这会改变通常不合需要的原始数组。我们可以通过在排序之前使用Array.prototype.slice创建原始数组的副本来缓解这个问题。由于我们正在创建一个全新的数组,我们将排序操作的结果存储在一个新变量中。

const sortedProjects = projects
  .slice()
  .sort((projectX, projectY) => projectX.title.localeCompare(projectY.title));

此处它对您的示例数据

采取行动

const projects = [{
    "href": "/cancerSimulation",
    "theclass": "p5js websites",
    "btnValue": "Cancer Simulator",
    "title": "Aancer Simulation",
    "description": "Cancer Simulation as addition to exam project Cancer Simulation as addition to exam project Cancer Simulation as addition to exam project Cancer Simulation as addition to exam project",
    "date": [2017, "2017", 5, "may"]
  },
  {
    "href": "/encryptionProject",
    "theclass": "websites",
    "btnValue": "Facebook Encryption Tool",
    "title": "Bacebook Encryption Tool",
    "description": "Facebook Encryption Tool",
    "date": [2016, "2016", 12, "December"]
  },
  {
    "href": "/encryptionProject",
    "theclass": "websites",
    "btnValue": "Facebook Encryption Tool",
    "title": "Dacebook Encryption Tool",
    "description": "Facebook Encryption Tool",
    "date": [2016, "2016", 12, "December"]
  },
  {
    "href": "/encryptionProject",
    "theclass": "websites",
    "btnValue": "Facebook Encryption Tool",
    "title": "Cacebook Encryption Tool",
    "description": "Facebook Encryption Tool",
    "date": [2016, "2016", 12, "December"]
  }
];

const sortedProjects = projects
  .slice()
  .sort((projectX, projectY) => projectX.title.localeCompare(projectY.title));
  
console.log(sortedProjects)

<强>说明:

在示例代码中,我使用const来声明我的本地人。当名称不会被反弹时,const优于let,因为它会立即向读者传达该信息。它使读者不必考虑引用 sortedProjects的当前状态,因为它们无法更改。请注意,引用的数组仍然是可变的。

slice创建数组的浅表副本或数组的子集。如果未指定参数,则只创建整个数组的浅表副本。通过浅拷贝,我的意思是只复制对数组中每个索引处的对象的引用。这两个数组仍然共享相同的底层对象,只是以不同的顺序排列。指向slice的MDN文档的内联超链接详细说明了此行为。

答案 1 :(得分:0)

您想要的是按键对数组进行排序。这可以很容易地完成,如下面的示例所示。在这种情况下,我们的密钥是字典的name

var projectsDATA = [
  {'name': 'X', 'value': 24},
  {'name': 'Y', 'value': 25},
  {'name': 'Z', 'value': 26},
  {'name': 'A', 'value': 1},
  {'name': 'B', 'value': 2},
  {'name': 'C', 'value': 3}
];

console.log(projectsDATA);

// Note ".slice()" which makes a shallow copy of your array

sorted = projectsDATA.slice().sort(function(a, b) {
  if (a['name'] < b['name']) return -1;
  if (a['name'] > b['name']) return 1;
  return 0;
});

console.log(sorted);

您可以使用函数sortByKey来概括它:

sortByKey = function(array, key) {
    return array.sort(function(a, b) {
      if (a[key] < b[key]) return -1;
      if (a[key] > b[key]) return 1;
      return 0;
    });
};

valuename排序:

console.log(sortByKey(projectsDATA, 'value'));
console.log(sortByKey(projectsDATA, 'name'));