javascript JS:遍历字符串,找到第一个字母,输出为关联字符串的字母组锚点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6957824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JS: loop through strings, find first letter, output as letter group anchor to associated string(s)?
提问by farsider
Scenario:I have content that is alphabetically output into a list from a resource library. I need to be able to loop through each element/item (e.g.: department name) in this list and group all starting with 'A' ('B', 'C', 'D', and so on) into its own class for anchor navigation. Then, I need to be able to find which letters were found and create group anchors.
场景:我的内容按字母顺序从资源库输出到列表中。我需要能够遍历此列表中的每个元素/项目(例如:部门名称),并将所有以“A”(“B”、“C”、“D”等)开头的内容分组到其自己的类中用于锚导航。然后,我需要能够找到找到的字母并创建组锚点。
Desired Output:At the top of the page, there is each letter of the alphabet found that has element(s) with that letter. Clicking on the letter will anchor to a section/div (new class) with all elements of the corresponding letter.
期望的输出:在页面顶部,找到的字母表中的每个字母都包含该字母的元素。单击字母将锚定到包含相应字母的所有元素的部分/div(新类)。
What I've Tried (to find the first letter and create a group):
我尝试过的(找到第一个字母并创建一个组):
for(var i=0; i<input_1.length; i++){ //input_1 is the name of the specific resource library
var firstChar = input_1[i].charAt(0)
var newGroup = firstChar + "_input_1";
if(typeof(window[newGroup]) == 'undefined') window[newGroup] = []; //if var doesn't exist, create it
window[newGroup].push(input_1[i]);
}
A_input_1 = []; //A-letter-specific group
I'm beside myself when it comes to creating an anchor from that group to the associated strings. Ideas?
在创建从该组到关联字符串的锚点时,我很不自在。想法?
回答by Ryan Ballantyne
You need to use DOM functions to manipulate the DOM. It's kind of a pain, actually. To be honest, I wouldn't mess with it; there are libraries that make things easier. Let's go with JQuery.
您需要使用 DOM 函数来操作 DOM。其实有点痛 老实说,我不会惹它;有一些库可以让事情变得更容易。让我们使用 JQuery。
Say your page has the following HTML:
假设您的页面具有以下 HTML:
<ul id="TheList">
<li>Auspicious</li>
<li>Brobdingnagian</li>
<li>Calico</li>
<li>Doppleganger</li>
<li>Etc.</li>
</ul>
JQuery code to manipulate it would look something like this (I have not tested this code to ensure it works):
操作它的 JQuery 代码看起来像这样(我没有测试过这段代码以确保它工作):
var previousFirst = null;
$('#TheList').each(function() {
var text = $(this).text();
if (previousFirst === null) previousFirst = $(this);
$(this).addClass(text.charAt(0) + '_input_1');
if (text.charAt(0) != previousFirst.text().charAt(0)) {
$('<a name="'+ previousFirst.text().charAt(0) +'"></a>').prependTo(previousFirst);
previousFirst = $(this);
}
});
If you're not familiar with JQuery, I encourage you to read up on it on jquery.com. Once you familiarize yourself with the workings of the library, the code should be clear and easy to understand. That said, if you need any clarification, feel free to ask and I'll do my best.
如果您不熟悉 JQuery,我鼓励您在 jquery.com 上阅读它。一旦熟悉了库的工作原理,代码就应该清晰易懂。也就是说,如果您需要任何说明,请随时提出,我会尽力而为。
回答by Andrew Hodgkinson
Off the top of my head I can't think of a native method that will do this more elegantly than a loop over all elements in the list. Performance may thus be an issue if you have a large number of items or on slow client browsers.
在我的脑海中,我想不出比循环遍历列表中的所有元素更优雅的本机方法。因此,如果您有大量项目或在缓慢的客户端浏览器上,性能可能是一个问题。
Bearing the above in mind, here's one approach:
考虑到上述情况,这里有一种方法:
var length = input_1.length;
var groups = {};
for ( var i = 0; i < length; i ++ )
{
var item = input_1[ i ];
var firstChar = item.charAt( 0 );
groups[ firstChar ] = groups[ firstChar ] || [];
groups[ firstChar ].push( item );
}
The value of 'length' is calculated externally as a very small optimisation in loops - JavaScript will re-evaluate the array length each time around the loop otherwise. Other than that, the end result from an input array of strings is that "groups" will have a series of keys / properties corresponding to all the used first letters of the input strings and each of those keys has, as its value, an array of the grouped strings. Sorting is not attempted.
'length' 的值是作为循环中非常小的优化在外部计算的 - JavaScript 将在每次循环时重新评估数组长度,否则。除此之外,输入字符串数组的最终结果是“组”将具有与输入字符串的所有使用的第一个字母相对应的一系列键/属性,并且这些键中的每一个都具有作为其值的数组分组的字符串。不尝试排序。
Example:
例子:
input_1 = [ "hello", "an", "cat", "hi", "henry", "thing", "anchor" ];
=> groups[ "a" ] is [ "an", "anchor" ]
groups[ "c" ] is [ "cat" ]
groups[ "h" ] is [ "hello", "hi", "henry" ]
groups[ "t" ] is [ "thing" ]