(1)一個(gè)返回給定范圍拌阴,給定個(gè)數(shù)不重復(fù),從小到大排列的數(shù)組的函數(shù)
在慕課問答里面看到的怀读,很有趣,我使用for循環(huán)來的骑脱,沒解決當(dāng)有相同值的時(shí)候再進(jìn)行取隨機(jī)值菜枷,所以會(huì)出現(xiàn)數(shù)組長(zhǎng)度不夠,但是用while可以解決
function getRadNum(min,max,num){
var min_c = min || 0;
var max_c = max || 10;
var num_c = num || 1;
var num_arr = [];
while(num_arr.length < num_c){
var rad = Math.floor(Math.random() * max_c + min_c);
if(num_arr.indexOf(rad) == -1){
num_arr.push(rad);
}
}
return num_arr.sort(function(a,b){return a-b});
}
console.log(getRadNum(15,30,5));
//要記得對(duì)輸入?yún)?shù)的類型叁丧,范圍做校驗(yàn)
當(dāng)沒傳入任何參數(shù)的時(shí)候啤誊,會(huì)在0到10之間隨機(jī)取一個(gè)數(shù)
(2)判斷亂序的兩個(gè)字符串是否是完全相同
先將傳如的字符串進(jìn)行轉(zhuǎn)小寫
然后拆分成數(shù)組,再進(jìn)行排序(是按照ascii),拼接成字符串(很多關(guān)于字符串操作的函數(shù)都涉及到split,join)
var str1 = "ambtiino";
var str2 = "mabitoin";
function strIsSame(firstStr,secondStr){
var first = firstStr.toLowerCase();
var second = secondStr.toLowerCase();
first = first.split("").sort().join("");
second = second.split("").sort().join("");
return first == second;
}
console.log(strIsSame(str1,str2)) //true
(3)爛大街的數(shù)組亂序
var arr_de = [1,2,3,4,5,6,7,8,9];
console.log(arr_de.sort(function(a,b){
return Math.random() > 0.5?1:-1;
}))
(4)既然有數(shù)組歹袁,也有字符串亂序坷衍,相似的
var str8 = "westpointlalala";
function unorderstr(str){
return str.split("").sort(function(a,b){return Math.random()>0.5?1:-1}).join("");
}
console.log(unorderstr(str8));
join()里面什么都不加的時(shí)候是用逗號(hào)連接
(5)字符串倒序,回文檢測(cè)条舔,一樣的原理
var str = "westpoint";
function strto(str){
return str.split("").reverse().join("");
}
console.log(strto(str));
(6)隨機(jī)返回不是0就是1
console.log(Math.round(Math.random()));
(7)字符串轉(zhuǎn)數(shù)字
function toNumber(number){
return +number;
}
console.log(toNumber("5743"));
(9)找出1到10000之中的對(duì)稱數(shù)枫耳,如121,1221
還可以toString()
var arrsame = [];
for (var i = 1;i <=10000;i++) {
var num = i + "";
if(num.split("").reverse().join("") === num){
arrsame.push(num);
}
}
console.log(arrsame);
(10)箭頭sort()
[7,9,10,18,5,6,21].sort((a,b)=>a-b) //[5, 6, 7, 9, 10, 18, 21]
(11)得到數(shù)組中每個(gè)元素的數(shù)量
var arr=['p','p','s','m','j','s'];
function getArrNum(array){
var result = {};
for(var i = 0;i < array.length;i++){
if(!result[array[i]]){
result[array[i]] = 1;
}else{
result[array[i]]++;
}
}
for(item in result){
console.log(item + ":" + result[item]);
}
}
getArrNum(arr);
(12)不用循環(huán)創(chuàng)建0到99的值與索引相同的數(shù)組
var hundred = new Array(100).join("").split(",").map(function(item,index){
return index;
});
hundred.forEach(function(item,i){
return console.log(item);
})