Underscore.js _.indexBy函数
Underscore.js是一个JavaScript库,它提供了很多有用的功能,对编程有很大的帮助,如地图、过滤器、调用等,甚至不使用任何内置对象。
_.indexBy()函数用于为列表中的每个元素返回一个键,然后返回一个具有每个项目索引的对象。它根据参数中给出的属性给出结果。另外,它与groupBy()函数类似,但每个项目在开始时都有一个索引。所传递的数组必须有唯一的属性(需要作为参数传递的属性)。如果该属性不是唯一的,那么输出将是最后一个匹配的元素。
参数:该函数接受上面提到的和下面描述的三个参数。
- list。该参数包含项目列表。
- iterate。该参数用于保持测试条件。
- context。该参数用于显示内容。
返回值:返回值是元素和它们的索引(参数中传递的属性)。
直接向_.indexBy()函数传递一个数组: _.indexBy()函数从列表中一个一个地获取元素,并且只是在结果中显示它和它们的索引。在遍历并显示所有元素及其索引后,sort By函数结束。然后只需通过 console.log() this.
示例:
<html>
<head>
<script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js">
</script>
</head>
<body>
<script type="text/javascript">
console.log(_.indexBy(['HTML', 'CSS3', 'JS', 'PHP']));
</script>
</body>
</html>
输出:
将一个有多个属性的数组传递给_.indexBy()函数:将一个有多个属性的数组(比如这里有3个属性)传递给indexBy()函数,然后只显示一个一个的元素和它们的索引。索引将根据参数中给出的属性来选择,比如这里的属性是’prop2’。因此,’prop2’的值将被作为结果中的索引。
示例:
<html>
<head>
<script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js">
</script>
</head>
<body>
<script type="text/javascript">
var arr = [
{prop1:"10", prop2:"07", prop3: "Geeks"},
{prop1:"12", prop2:"86", prop3: "for"},
{prop1:"11", prop2:"58", prop3: "Geeks."}
];
console.log(_.indexBy(arr, 'prop2'));
</script>
</body>
</html>
输出:
将一个带有’date’属性的结构传递给_.indexBy()函数:首先,声明数组(这里数组是’orders’)。该数组包含一个 “date “属性,其格式为日期。’dd-mm-yy’。然后将数组和结构传给_.indexBy()函数。Console.log得到最终答案。
示例:
<html>
<head>
<script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js">
</script>
</head>
<body>
<script type="text/javascript">
var orders = [
{ date:"30-60-90 Day", Name:"Kim", amount:415 },
{ date:"30-60-90 Day", Name:"Kelly", amount:175 },
{ date:"30 Day", Name:"Shelly", amount:400 },
{ date:"30 Day", Name:"Sarvesh", amount:180 }
];
console.log(_.indexBy(orders, 'date'));
</script>
</body>
</html>
输出:
将一个以’true’/’false’为属性的数组传递给_.indexBy()函数 :声明一个数组(比如这里的’people’),其中一个属性为’true’/’false’。这就是定义索引的属性,也就是说,现在,索引将是真或假。也不是说因为这个属性中存在重复,因为有两个值:真,假,但有四个人。所以,只有最后一个具有false(/true)的元素会在结果中显示。
示例:
<html>
<head>
<script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js">
</script>
</head>
<body>
<script type="text/javascript">
var people = [
{"name": "sakshi", "hasLong": "false"},
{"name": "aishwarya", "hasLong": "true"},
{"name": "akansha", "hasLong": "true"},
{"name": "preeti", "hasLong": "true"}
]
console.log(_.indexBy(people, 'hasLong'));
</script>
</body>
</html>
输出: