是否有更有效的方法来选择对象数组中的特定对象
给定以下数据结构
var things = [{ "name": "thing1", "sex": "male"},
{ "name": "thing2", "sex": "female"}];
,我希望能够搜索该对象数组并提取特定对象。
我目前编写的 JsFiddle 代码
function selectElementByName (name) {
var returnObject;
for (var i = 0; i < things.length; i++) {
if (things[i].name === name) {
returnObject = things[i];
}
}
if ( returnObject === undefined) {
console.log("Object not found");
}
return returnObject;
}
可以在 这里 找到,
有没有更有效的方法这?
Given the following data structure
var things = [{ "name": "thing1", "sex": "male"},
{ "name": "thing2", "sex": "female"}];
I would like to be able to search that array of objects and pull out a particular object.
I currently have the following code written
function selectElementByName (name) {
var returnObject;
for (var i = 0; i < things.length; i++) {
if (things[i].name === name) {
returnObject = things[i];
}
}
if ( returnObject === undefined) {
console.log("Object not found");
}
return returnObject;
}
JsFiddle can be found here
Is there a more efficient way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在找到对象时提前退出,这样您就不必循环遍历数组的其余部分:(
但是,如果存在重复项,这将改变行为,以便它返回找到的第一个对象而不是最后一个。)
如果名称是唯一的,您可以使用它们作为键并将对象存储在对象中而不是数组中:
那么您不需要循环来查找对象:
如果您需要数组中的对象,如果数组没有改变,你仍然可以创建一个索引来搜索经常使用:
现在您可以使用索引来查找对象:
由于数组更改后您必须立即更新或重新创建索引,因此只有当您在数组中搜索的频率比更改数组的频率高得多时,这才有用。
You can make an early exit when an object is found, so that you don't have to loop through the rest of the array:
(This will however change the behaviour if there are duplicates, so that it returns the first object found instead of the last.)
If the names are unique, you could use them as key and store the objects in an object instead of in an array:
Then you wouldn't need to loop to find an object:
If you need the objects in an array, you could still create an index for searching if the array doesn't change so often:
Now you can use the index to find the object:
As you have to update or recreate the index as soon as the array changes, this would only be usedful if you do searches in the array much more often than you change the array.
在最新版本的 JavaScript 中:
In more recent versions of JavaScript:
一旦找到至少你可以打破:
You can break once it's found at least: