目前我的代码如下所示:
var arrayListEnum = list.getEnumerator();
while (arrayListEnum.moveNext()) {
var listItem = arrayListEnum.get_current();
if (listItem.get_id() == id) {
//stuff(listItem);
break;
}
}
也许我只是被 C# 宠坏了,但我不太喜欢它的外观。在 JavaScript 或 jQuery(我不想包含整个其他库)中,有没有办法让我做类似的事情:
var item = (from items in list.getEnumerator()
where items.get_id() == id
select items);
//stuff(item);
或
var item = list.getEnumerator().Where(item => item.get_id() == id);
//stuff(item);
提前致谢。
最佳答案
我猜你会得到list item collection从列表中,在这种情况下,如果您只对通过 id 获取列表项感兴趣,那么我建议使用 SP.List.getItemById Method ,例如:
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
function() {
console.log(item.get_id());
},
function(sender,args){
console.log(args.get_message());
});
Note: from performance perspective the advantage here that there is no need to request list item collection and then filter item on the client side
下面提供了一些示例,演示如何按属性查找/过滤集合中的列表项
1) 使用getEnumerator
方法
function findListItem(items,propertyName,propertyValue)
{
var e = items.getEnumerator();
while (e.moveNext()) {
var listItem = e.get_current();
if (listItem.get_item(propertyName) == propertyValue) {
return listItem
}
}
return null;
}
2)使用for
语句
function findListItem(items,propertyName,propertyValue)
{
for(var i = 0; i < items.get_count();i++) {
var listItem = items.get_item(i);
if (listItem.get_item(propertyName) == propertyValue) {
return listItem
}
}
return null;
}
3)使用filter() method :
//returns array(!)
function findListItem(items,propertyName,propertyValue)
{
return items.get_data().filter(function(item){
if (item.get_item(propertyName) == propertyValue) {
return item
}
});
}
关于javascript - 当查找具有特定属性的对象时,是否有类似 LINQ 的替代方法可以替代 JavaScript 中的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30264613/