Check if ID exists, and then rename it

回眸只為那壹抹淺笑 提交于 2019-12-11 01:43:30

问题


I'm trying to detect duplicate IDs,

http://jsfiddle.net/HB7ev/10/

And if I understand correctly:

if (id in dupeUIDCheck) 

Checks if the value of id is in the array: dupeUIDCheck, however, it seems that the:

dupeUIDCheck[id] = true;

that is set at the end actually makes the check work.

It doesn't really look inside the:

dupeUIDCheck = $(document).find('DIV')
            .map(function(){ return this.id || undefined})
            .toArray();

for values, that I call first.

How can I fix this? For some reason I do have it working in one part of my own website, so the makeIdUnique() seems to be working like it should, but why doesn't it in this example? (maybe a malformed array?)

The original function was forked from a previous problem: Renaming duplicates in Javascript Array


回答1:


@TrySpace

As I understand "dupeUIDCheck" is a regular array. If this is true, then you need to use Array.prototype.indexOf method:

if (dupeUIDCheck.indexOf(id) != -1) {
 ...
}

This piece of code "dupeUIDCheck[id] = true;" fixes the problem because you are defining property on array object itself and "in" operator will obviously confirm that such property exists, though, this is not true for array elements. "in" operator doesn't lookup inside array elements.




回答2:


You can use

$.inArray(id, dupeUIDCheck)

or

dupeUIDCheck.indexOf(id);

Note

As dupeUIDCheck is an Array, so to find an element within an array exists or not, you need to use indexOf(). .indexOf() returns index of the searched element within that array if found or -1 if not found. $.inArray(value, array) is jQuery method which do similar job as .indexOf().


That is

function makeIdUnique(id) {

   if (dupeUIDCheck.indexOf(id) >= 0) {  // exists
     // your code
   } 

}

or

function makeIdUnique(id) {

   if ($.inArray(id, dupeUIDCheck) >= 0) {  // exists
     // your code
   } 

}

id in dupeUIDCheck works for Object like

var obj = {a: 'abc', b: 'def'};

Then to search a property of object you can use

if( 'a' in obj) {

}


来源:https://stackoverflow.com/questions/10962412/check-if-id-exists-and-then-rename-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!