问题
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