简体   繁体   English

如何检查字符串中的第一个字符以及如何将该字符串发送到 Jquery 中的数组中?

[英]How to check first character in string and how to send that string into an array in Jquery?

friends.朋友们。

I have an array and it contains some string values.我有一个数组,它包含一些字符串值。 ex: array name="All_array"例如:数组名称="All_array"

Now i want to check all values in that array for first character of a string.现在我想检查该数组中的所有值是否为字符串的第一个字符。

if a String starts with character 'a' then move that string to array called "A_array".如果字符串以字符“a”开头,则将该字符串移动到名为“A_array”的数组中。 if a String starts with character 'b' then move that string to array called "B_array".如果字符串以字符“b”开头,则将该字符串移动到名为“B_array”的数组中。

How to achieve this task.如何完成这个任务。

var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
    var firstChar = All_array[i].substr(0,1).toUpperCase();
    if(!splitArrays[firstChar + '_array'])
        splitArrays[firstChar + '_array'] = [];
    splitArrays[firstChar + '_array'].push(All_array[i]);
}

This will take every element in All_array and put them into an object containing the arrays indexed by the first letter of the elements in All_array , like this:这将获取 All_array 中的每个元素并将它们放入All_array中,其中包含由 All_array 中元素的第一个字母索引的All_array ,如下所示:

splitArrays.A_array = ['Abcd','Anej','Aali']

etc... ETC...

Here's a fiddle: http://jsfiddle.net/svjJ9/这是一个小提琴: http://jsfiddle.net/svjJ9/

The code would be this:代码是这样的:

for(var i=0; i<All_array.length; i++){
   var firstChar = All_array[i].substr(0, 1).toUpperCase();
   var arrayName = firstChar + "_array";
   if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
   window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')

Hope this helps.希望这可以帮助。 Cheers干杯

You could do it using each() and charAt :您可以使用each()charAt来做到这一点:

$.each(All_array,function(i,s){  
    var c = s.charAt(0).toUpperCase();                
    if(!window[c + '_array']) window[c + '_array'] = [];
    window[c + '_array'].push(s);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM