$ .inArray()循环问题的更好的语法

时间:2014-04-13 04:38:15

标签: javascript jquery loops

我试图使用$ .inArray的循环。基本上,我有我循环的信息,我需要获取一部分信息并将其添加到数组中。如果该区域已经存在该信息(有重复项,相同的三项,相同的四项,等等,直到同一数据的12个实例),我会在数据末尾附加一个数字。数据,以确定它是什么重复。这是我的代码:

var subject_name_original = subject_name;    

if ($.inArray(subject_name, subject_array) !== -1){
    subject_name = subject_name_original + '2';
    if ($.inArray(subject_name, subject_array) !== -1){
        subject_name = subject_name_original + '3';
        if ($.inArray(subject_name, subject_array) !== -1){
            subject_name = subject_name_original + '4';
        }
     }
}

subject_array.push(subject_name);

这一直循环到12个实例,因此您可以看到它的编写方式不是很有效。我想使用一个计数器变量来增加附加的数字,但不知道如何在这样的循环中使用inArray。

有什么想法吗?谢谢你的帮助!

3 个答案:

答案 0 :(得分:2)

你可以这样做:

var subjectCounter = 1;
var originalSubjectName = subjectName;
while (subjectArray.indexOf(subjectName) !== -1) { // $.inArray is the same as this
    subjectCounter += 1;
    subjectName = originalSubjectName + subjectCounter;
}
subjectArray.push(subjectName);

答案 1 :(得分:0)

如果未对subject_array进行排序,请先对其进行排序。然后你应该只需要访问一次。

var sorted = subject_array.sort();
var subject_counter = 1;
var subject_name_original = subject_name;

for (var i = sorted.length - 1; i >= 0; i--) {
  if (sorted[i] == subject_name) {
    subject_counter++;
    subject_name = subject_name_original + subject_counter;
  };
};

subject_array.push(subject_name);

答案 2 :(得分:0)

这个应该有效(未经测试):

var i = 1;
var subject_name_original = subject_name;
while (++i < 13) { // at first loop, i = 2
    if ($.inArray(subject_name, subject_array) !== -1) {
        subject_name = subject_name_original + i;
    } else {

        // $.inArray() failed beyound the second loop :

        if (i > 3) {
            subject_name = subject_name_original + (i - 1);
            subject_array.push(subject_name);
        }

        // $.inArray() failed at second loop (i = 3) :

        else if (i > 2) {
            subject_name = subject_name_original;
            subject_array.push(subject_name);
        }

        // Does nothing if $.inArray() failed at first loop.

        break;
    }
}