jQuery脚本不适用于预填充的数组
jQuery script not working with pre populated Array
我希望我没有重复现有的问题,我已经非常努力地在网站上找到我需要的东西,但现在我觉得我需要问这个问题,所以我希望你们能帮助我: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;
});
我可以在您的代码中看到两个问题。
- 变量名不能以数字开头
- 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非常感谢:)我需要一个假期。。。。
- 用每小时的差值填充数组/列表-从下拉列表中给定两个时间值
- 用默认值填充数组的方法
- 在 Javascript 中使用 ForEach 填充数组对象时,我是否需要定义一个数组对象
- 用当前日期填充数组并继续向后
- 用字符串填充数组的最佳方法
- Javascript 填充数组使用 for 循环
- PHP 无法从选定的表中填充数组以json_encode并在 javascript 上接收它
- Javascript/JQuery 填充数组许多元素
- 将字符串添加到已填充数组的数组中
- jQuery根据第一个输入的文本框值填充数组命名的表单字段
- 更改Img属性时出现填充数组错误
- 用对象填充数组(在对象中定义)
- 如何填充数组循环JS
- 如何实现迭代的、填充数组的Angular 2输入
- 在Javascript中基于其他信息填充数组的最有效方法是什么?
- 从多个mongodb调用填充数组的范围问题
- 动态创建的带有填充数组的下拉列表不会使用angular更新
- 我如何填充数组与二进制数据流从websocket
- 填充数组类型嵌套对象时出现的问题
- 从lodash填充与常规数组填充数组时产生的不希望的结果