一、选出出现最多次数的字母,并输出它和出现次数
<script>
let a = "aaabbbbbcccdddeeeeefff";
let obj = {};
let char;
for (let i = 0; i < a.length; i++) {
char = a.charAt(i);
if (obj[char]) {
obj[char]++;
} else {
obj[char] = 1;
}
}
let maxNum = 0;
let maxChar;
for (let key in obj) {
if (maxNum < obj[key]) {
maxNum = obj[key];
}
}
for (let key in obj) {
if (maxNum == obj[key]) {
maxChar = key;
console.log("出现次数最多的字符", maxChar);
console.log("出现次数最多的次数", maxNum);
}
}
</script>
这里关键点是把a字符串中的每一个字符及出现的次数记录下来,而了解对象中是可以通过obj[key]=value
的方式去进行插值,比如下列
<script>
let obj = {};
function hand(key, value) {
obj[key] = value;
}
hand("a", 2);
console.log(obj);
</script>
只要再得到新对象是每个字符出现的次数就可以了
二、查找数组中出现次数最多的数字,输出它与次数
<script>
let a = [1, 1, 1, 1, 2,2,2,2, 2, 3, 4, 5, 6, 1];
let obj = {};
a.forEach((item, index) => {
if (a.indexOf(item) !== index) {
obj[item]++;
} else {
obj[item] = 1;
}
});
let max =0
let maxNum
for(let key in obj){
if(max<obj[key]){
max=obj[key]
}
}
for(let key in obj){
if(max==obj[key]){
maxNum=key
console.log('出现次数最多的数字',max);
console.log('出现次数最多的次数',maxNum);
}
}
</script>
这里也是利用了对空对象进行添加的一种方式
三、两组数组,输出相同的数字
<script>
let a =[1,1,1,2,2,3,3,4]
let b =[1,2,3,6,6,6]
let c= Array.from(new Set(a))
let d= Array.from(new Set(b))
let e =[...c,...d]
let f =[]
e.forEach((item,index)=>{
if(e.indexOf(item)!==index){
f.push(item)
}
})
console.log(f);
</script>
四、将一维数组拆分为指定长度二维数组
<script>
function hand(arrayList, tig) {
let index = 0;
let newValue = [];
while (index < arrayList.length) {
newValue.push(arrayList.slice(index, (index += tig)));
}
console.log(newValue);
return newValue;
}
hand([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3);
</script>