javascript arrays and/or jquery $.inArray() and .splice()
javascript arrays and/or jquery $.inArray() and .splice()
我正在使用一个数组,它只能有12个值;1到12。这些值可以以任意顺序存在。我需要遍历数组并找到第一个未使用的值,然后将其设置为一个变量。
例如,如果数组包含值[1,7,2,5,10],我想将变量设置为3,因为它是按数字顺序排列的第一个未使用的数字。我正在使用jQuery 1.9.1和jQuery UI 1.10.1,但如果这可以在纯javascript中解决,那就太好了!
下面是我的代码,我知道这是错误的,因为它总是设置变量为1。注意:tCounter是一个在几个函数中使用的全局数组,所以我不想修改这里的内容。这就是为什么我创建了tArray来拼接值。谢谢你的帮助!
var i;
var t;
var tArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
for (i = 1; i < 12; i++) {
if (jQuery.inArray(i, tCounter)) {
tArray.splice($.inArray(i, tArray), 1);
}
}
if (tArray.length <= 0) {
term = 1;
} else {
term = tArray[0];
}
在您当前的实现中,我可以看到两个错误。
首先,您的for
循环索引似乎是一次性的。在当前状态下,它将不检查数字12是否存在(由于您的条件i<12
)。
第二,你的if
语句实际上计算为假,而它应该是真的。如果数组中的索引为0 (Javascript中0的值为false),则应该输入该语句。我将把你的代码重写如下:
var i;
var t; //this isn't used, perhaps it should be 'term'?
for (i = 1; i < 13; i++) {
// if we find a number that isn't in tCounter, we exit the loop.
if (jQuery.inArray(i, tCounter) === -1) {
term = i;
break;
}
//sets term to null if all numbers are present in array.
term = null;
}
如果您的值不是数字1-12,而是任意数字,那么您从数组中拼接值的想法将很好地工作,但实际上,您根本不需要var tArray。
旁注:在一个有趣的比较中,似乎如果你正在寻找最快的实现,你应该使用tCounter.indexOf(i)
而不是jQuery.inArray(i, tCounter)
,我不确定哪个更快,但这个漂亮的测试证实了我的怀疑。
一个简单的解决方案是从1-12迭代,并检查该值在数组中是否存在。这样的:
var i;
for(i=1; i<12; i+=1) {
if (tArray.indexOf(i) === -1) break;
}
term = i;
相关文章:
- Selenium WebDriver and JavaScript change
- jQuery$.inArray()总是返回-1和一个对象数组
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Rails 3.2 and Paloma gem
- Backbone, TypeScript, and super
- iframe and JavaScript on different pages
- JS - jQuery inarray ignoreCase() and contains()
- javascript arrays and/or jquery $.inArray() and .splice()