首頁 >web前端 >js教程 >把字串按照特定的字母順序進行排序的js程式碼_javascript技巧

把字串按照特定的字母順序進行排序的js程式碼_javascript技巧

WBOY
WBOY原創
2016-05-16 17:01:561469瀏覽

例如,給一個特定的字母順序,"a","o","e","u","y","i",請把'aiye','oeu','ayo','eoyiu' ,'yuo','you','iao'這7個字串依照給定的字母順序排序。

我的思路是把那幾個給定的6個字母分別等效成0-5的數字,然後把那7個字串中的字母替換成0-5中的數字,再用sort方法排序,程式碼如下:

複製程式碼 程式碼如下:
var word = ['aiye','oeu','ayo','eoyiu','yuo','you','iao'];
var obj = {a:0,o:1,e:2,u :3,y:4,i:5};
var obj1 = {0:'a',1:'o',2:'e',3:'u',4:'y',5 :'i'};
for(var index in word){
var word1 = word[index];
var word3 = "";
for(var i = 0; iword3 = obj[word1[i]];
};
word[index] = word3
}
word.sort();
for (var index in word){
var word1 = word[index];
var word3 = "";
for(var i = 0; iword3 = obj1[word1[i]];
};
word[index] = word3
}
console.log(word);


複製代碼 代碼如下:
<span class="source-code" style="font-family:Consolas,'Lucida Console',monspace; white-space: pre-wrap"><span style="font-family:Consolas,'Lucida Console',monospace; white-space:pre-wrap"></span></span><pre code_snippet_id="173179" snippet_file_name=" blog_20140127_1_4210131">

 
 
 
 
 
 
 
 



陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn