jQuery脚本不适用于预填充的数组

jQuery script not working with pre populated Array

本文关键字:填充 数组 适用于 脚本 不适用 jQuery      更新时间:2023-09-26

我希望我没有重复现有的问题,我已经非常努力地在网站上找到我需要的东西,但现在我觉得我需要问这个问题,所以我希望你们能帮助我:s

我有一个数组;

var 1Results = somecontent;
var 2Results = somecontent;
var 3Results = somecontent;
var 4Results = somecontent;
var nomResults = 1Results + 2Results + 3Results + 4Results;

我有一个脚本,应该剔除重复的数字并显示它们(在sorted_arr中);

    var arr = nomResults;
    var sorted_arr = arr.sort(); // You can define the comparing function here. 
                                 // JS by default uses a crappy string compare.
    var results = [];
    for (var i = 0; i < arr.length - 1; i++) {
        if (sorted_arr[i + 1] == sorted_arr[i]) {
            results.push(sorted_arr[i]);
        }
    }

这个脚本不起作用,但是我把脚本改成了这个;

    var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
    var sorted_arr = arr.sort(); // You can define the comparing function here. 
                                 // JS by default uses a crappy string compare.
    var results = [];
    for (var i = 0; i < arr.length - 1; i++) {
        if (sorted_arr[i + 1] == sorted_arr[i]) {
            results.push(sorted_arr[i]);
        }
    }

它工作得很好,你知道为什么.sort()不能用我的预流行数组吗?

如有任何帮助,我们将不胜感激。

您必须使用括号符号将元素添加到新数组中,如:

var arr = [Results1, Results2...];

Array.prototype.push():

var arr = [];
arr.push(Results1);
arr.push(Results2);
//...

此外,您可以使用特定的函数进行排序,或者声明一个新的函数compare:

function compare(a, b) {
  return a - b;
}

它将使用数组的实际值(而不是注释中指定的字符串)。然后你把它传给排序:

arr = arr.sort(compare);

或者直接使用匿名功能,如果您不需要它超过一次:

arr = arr.sort(function(a, b) {
  return a - b;
});

我可以在您的代码中看到两个问题。

  1. 变量名不能以数字开头
  2. var nomResults不是数组,而是字符串

下面的代码对我来说很好-

var results1 = "this", results2="is", results3="an", results4="array", theArray = [results1, results2, results3, results4];

console.log(theArray);

["this"、"is"、"an"、"array"]

console.log(theArray.sort());

["an","array","is","this"]

我构建的数组错误!!!谢谢大家,我知道这会很简单:)

相反;

var nomResults = 1Results + 2Results + 3Results + 4Results;

我需要这样做;

var nomResults = [Results1, Results2, Results3, Results4];

我看了这么长时间了,我没有看到。我的剧本现在都在运行,很棒,错误都消失了,这太神奇了。很多道具,感谢@jpreynat非常感谢:)我需要一个假期。。。。