我们可以借助_.ware()函数找到具体的条件。
_.where()属于underscore.js,一个提供多种功能的javascript库。 _.where()是一个函数,用于根据给定的条件查找特定元素。
假设您要查找该类的所有用户详细信息,然后将 _.where() 函数应用于所有部分的列表,并将条件作为部分名称传递。因此将返回所有符合特定条件的用户的名称。
语法
_.where( list, [predicate], [context] )
登录后复制
该函数接受三个参数作为参数。
立即学习“Java免费学习笔记(深入)”;
List– 用于保存数据列表的参数。
谓词– 此参数保存测试条件。
上下文– 我们需要显示的文本。
返回值− 该函数返回所有符合条件的值。
示例 1:将数组传递给 _.where() 函数
_.where()函数逐一获取数组的元素并匹配指定的条件。长是真还是假。如果匹配,则返回该值。
var users = [ { name: "priya", Long: "false" }, { name: "aishwarya", Long: "true" }, { name: "akanksha", Long: "true" }, { name: "ruby", Long: "true" }, ]; document.write(JSON.stringify(_.where(users, { Long: "true" })));
登录后复制
示例 2
在下面的示例中,我们将具有多个属性的元素列表传递给 _.where() 函数 –
var details = [ { "city": "Ranchi", "state": "Jharkhand", "id": "1" }, { "city": "Jamshedpur", "state": "Jharkhand", "id": "2" }, { "city": "Hyderabad", "state": "Telangana", "id": "3" }, { "city": "Delhi", "state": "Delhi", "id": "4" }, { "city": "Delhi", "Pune": "Maharastra", "id": "5" } ]; document.write(JSON.stringify(_.where(details,{state:"Jharkhand"})));
登录后复制
示例:3
在此示例中,我们将一个以数字作为其属性之一的数组传递给 _.where() 函数 –
var users = [ { id: 1, name: "priya" }, { id: 2, name: "aishwarya" }, { id: 3, name: "akanksha" }, { id: 4, name: "ruby" }, { id: 5, name: "Aman" }, ]; document.write(JSON.stringify(_.where(users, { id: 5 })));
登录后复制
示例 4:_.where() 函数作为 _.findWhere() 函数
我们可以使用 _.findWhere() 函数代替 _.where() 函数,因为两者给出相同的输出。
var users = [ { id: 1, name: "priya" }, { id: 2, name: "aishwarya" }, { id: 3, name: "akanksha" }, { id: 4, name: "ruby" }, { id: 5, name: "Aman" }, ]; document.write(JSON.stringify(_.findWhere(users, { id: 5 })));
登录后复制
示例 5:使用 _.filter() 方法
在本例中,我们将使用 _.filter()方法来检查数组中的元素是否满足条件。
_.filter() method example let arr = [2, 4, 6, 8, 10]; let flag = false; let getEvenNum = _.filter(arr, function (num) { return num % 2 == 0; }); if (JSON.stringify(getEvenNum) === JSON.stringify(arr)) { flag = true; } document.getElementById("filter").innerHTML ="The array elements passed the condition : " + flag;
登录后复制
示例 6:使用 every() 方法
在本例中,我们将使用 array.every() 方法来检查数组中的元素是否满足条件。
Array.every() method example let arr = new Array(2, 4, 6, 8, 10); let getEvenNum = arr.every(function (num) { return num % 2 == 0; }); document.getElementById("every").innerHTML ="The array elements have passed the condition : " + getEvenNum;
登录后复制
示例 7:使用 for 循环
现在让我们看一个使用 for 循环的示例 –
Using for loop example let arr = new Array(2, 4, 6, 8, 10); let flag = true; for (let i = 0; i 10) { flag = false; break; } } document.getElementById("every").innerHTML = "The array elements have passed the condition : " + flag;
登录后复制
以上就是JavaScript 中如何找出与特定条件匹配的所有元素?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2694631.html