JavaScript:查找值是不是在数组中的对象内的最佳方法[重复]
Posted
技术标签:
【中文标题】JavaScript:查找值是不是在数组中的对象内的最佳方法[重复]【英文标题】:JavaScript: Best way to find if a value is inside an object in an array [duplicate]JavaScript:查找值是否在数组中的对象内的最佳方法[重复] 【发布时间】:2011-12-09 05:35:53 【问题描述】:可能重复: Find object by id in an array of javascript objects How to check if value exists in this JavaScript array?
例如:
var arr = [
id: 1, color: 'blue',
id: 2, color: 'red',
id: 3, color: 'yellow'
];
alert( indexOf('blue') ); // How can I get the index of blue??
【问题讨论】:
可能的重复:***.com/questions/7740241/…, ***.com/questions/7364150/… 是 JSON 格式,你想获取 ID 吗? @sll:看起来不像 JSON。 【参考方案1】:您可能想要创建一个更通用的解决方案,而不是到处复制代码
Array.prototype.indexOf = (function()
var old = Array.prototype.indexOf ||
function(v)
var i, l = this.length;
for (i = 0; i < l; ++i)
if (this[i] === v)
return i;
return -1;
;
return function(v)
var i, l;
if (typeof v != "function")
return old.call( this, v );
l = this.length;
for( i = 0; i < l; ++i )
if (v.call( this, this[i]))
return i;
return -1;
)();
arr.indexOf( function(v)return v.color == "blue"; ); //0
arr.indexOf( function(v)return v.images[0].imageData == "xxx";
【讨论】:
【参考方案2】:found_flag = false;
for (i = 0; i < arr.length; i++)
if (arr[i].color == 'blue')
found_flag = true;
break;
if (found_flag === true)
alert(i);
else
alert('not found');
【讨论】:
【参考方案3】:非常糟糕的方法:
var ind = -1
$(arr).each(function(index, val)if (val.color=='blue')ind=index;return false;);
更好的方法可能是创建另一个可搜索的值映射及其索引,或类似的东西。
【讨论】:
【参考方案4】:只需循环遍历数组并检查颜色值:
for(var i = 0 ; i < arr.length -1 ; i++)
if(arr[i].color == 'red')
alert(i);
当然你也可以把它包装在一个辅助函数中,如下所示:
function colourIndex(colour)
for(var i = 0 ; i < arr.length -1 ; i++)
if(arr[i].color == colour)
return i;
【讨论】:
【参考方案5】:您必须遍历数组,搜索蓝色对象。如果你得到它,你有你的索引。
var index = 0;
for(; index<arr.length; index++)
if(arr[index].color == 'blue')
break;
alert(index)
【讨论】:
以上是关于JavaScript:查找值是不是在数组中的对象内的最佳方法[重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何通过猫鼬(javascript)中的多个值查询数组内的对象?