有沒有人來解釋一下這些代碼?這節(jié)實在看不懂啊
? <script type="text/javascript">
? ? //創(chuàng)建數(shù)組
? ? var arr=["*","##","***","&&","****","##*"];
? ? arr[7]="**";
? ??
? ? //刪除數(shù)組中非*的項
? ? for(var i=0;i<arr.length;i++){
? ? ? ? if(arr[i]!=undefined){
? ? ? ? ? ? var myarr=arr[i].split("");
? ? ? ? ? ? for(var j=0;j<myarr.length;j++){
? ? ? ? ? ? ? ? if(myarr[j]!='*'){
? ? ? ? ? ? ? ? ? ? arr.splice(i,1);
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? //按照字符數(shù)排序
? ? arr.sort(function(a, b){
? ? ? ? if(a.length>b.length)
? ? ? ? {
? ? ? ? ? ? return 1;
? ? ? ? }
? ? ? ? else if(a.length<b.length)
? ? ? ? {
? ? ? ? ? ? return -1;
? ? ? ? }
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? return 0;
? ? ? ? }
? ? })
? ? //將數(shù)組內(nèi)容輸出,完成達(dá)到的效果。
? ? for(var i=0;i<arr.length;i++){
? ? ? ? if(arr[i] != undefined){
? ? ? ? ? ? document.write(arr[i]+'<br />')
? ? ? ? }
? ? }
? ?</script>
2016-07-18
?var arr=['*','##','***','&&','****','##*'];
?arr[7]="**";
document.write(arr[0]+"<br/>") //輸出:*
document.write(arr[7]+"<br/>")//輸出:**
document.write(arr[2]+"<br/>")//輸出:***
document.write(arr[4]+"<br/>")//輸出:****
其實這樣的代碼就可以按要求打印結(jié)果,不過樓上的各種回答加上了判斷機制,一是判斷有沒有超出數(shù)組長度,二是判斷打印的結(jié)果是不是*。
2016-07-10
注釋得應(yīng)該可以看懂
2016-07-08
樓上正解
2016-07-07
這個代碼其實有一個bug,在刪除數(shù)組其中一個元素之后會改變數(shù)組的長度,導(dǎo)致for循環(huán)出錯
建議在arr.splice(i,1); 與break;中添加一句i--;
讓當(dāng)前的index減一
假如刪除數(shù)組index=3的位置,就再次從3開始下一次判斷
2016-07-06
split 分割字符串返回數(shù)組? splice刪除數(shù)組制定位置開始指定長度的的的元素
2016-07-06
根本沒有必要這么復(fù)雜!我的處理:
document.write(arr[0]+"<br/>") //輸出:*
document.write(arr[7]+"<br/>")//輸出:**
document.write(arr[2]+"<br/>")//輸出:***
document.write(arr[4]+"<br/>")//輸出:****
2016-07-06
我也是懵懵懂懂的,需要自己多看幾遍就理解了