用于循环将所有对象值设置为最后一个实例

时间:2017-04-05 19:07:43

标签: javascript

我试图迭代for循环以对数组进行5次排序。

let sortedCities = {};
for (let i = 0; i < 5; i++) {
  sortedCities[i] = darkSkyHelper.sortCities(info,unsortedCities,i);
  console.log(sortedCities[i]);
}
console.log(sortedCities);

static sortCities(info, cities, day) {
    let sortedCities = cities.sort(function(a,b) {
      return info[b].daily.data[day].precipProbability - info[a].daily.data[day].precipProbability;
    })
    return sortedCities;
  }

第一个console.log显示每个循环的预期输出,而第二个显示一个对象,每个对象的值等于上一次循环运行的输出

["cin", "cle", "col", "nya", "laa", "was", "tex"]
["was", "nya", "cle", "cin", "col", "laa", "tex"]
["cle", "cin", "was", "nya", "laa", "col", "tex"]
["laa", "col", "cle", "cin", "was", "nya", "tex"]
["col", "tex", "cle", "laa", "cin", "was", "nya"]

Object {..}
0: Array[7]
0: "col"
1: "tex"
2: "cle"
3: "laa"
4: "cin"
5: "was"
6: "nya"
length: 7
__proto__: Array[0]
1: Array[7]
0: "col"
1: "tex"
2: "cle"
3: "laa"
4: "cin"
5: "was"
6: "nya"
...

1 个答案:

答案 0 :(得分:1)

每次调用sortCities时,您都会返回对同一数组的引用,只是进行了不同的排序。您需要每次都创建一个新数组。有几种方法可以做到这一点,包括slice

static sortCities(info, cities, day) {
    let sortedCities = cities.sort(function(a,b) {
      return info[b].daily.data[day].precipProbability - info[a].daily.data[day].precipProbability;
    })
    return sortedCities.slice(0);
}