1、給定一個(gè)數(shù)組,計(jì)算出這個(gè)數(shù)組的所有數(shù)字相加的總和声搁。
function sumArr(arr) {
let sum = 0
arr.forEach(item=>{
sum+=item
})
return sum
}
////
function sumArr(arr) {
return arr.reduce((a,b)=>a+b)
}
/////
2數(shù)一數(shù)數(shù)組有幾個(gè)true
function countSheeps(arrayOfSheep) {
return arrayOfSheep.filter(e => e === true).length
}
///
function countSheeps(arrayOfSheep) {
// TODO May the force be with you
let num=0
arrayOfSheep.forEach(item=>{
if(item){
num++
}
})
return num
}
3數(shù)組去重并排序
function setArr(arr) {
return Array.from(new Set(arr)).sort((a,b)=>a-b)
}
///
function setArr(arr) {
var result = []
arr.forEach(item=>{
if(result.indexOf(item)==-1){
result.push(item)
}
})
return result.sort(function(a,b){
return a-b
})
}
4找到最短的單詞
function findShort(s){
var strArr = s.split(" ");
//將字符串長(zhǎng)度诅炉,另存一個(gè)數(shù)組
var lenArr = strArr.map(function(item){
return item.length;
});
var num = Math.min.apply(null, lenArr);
return num;
}
/////
function findShort(s){
return s.split(' ').sort((a, b) => a.length -b.length)[0].length
}
5重復(fù)字符函數(shù)
function repeatStr (n, s) {
return s.repeat(n);
}
////
function repeatStr (n, s) {
let strbox = '';
for(let i = 0; i < n; i++){
strbox += s;
}
return strbox;
}
6找規(guī)律寫(xiě)函數(shù)
a => A
ab => A-Bb
abc => A-Bb-Ccc
AbCd => A-Bb-Ccc-Dddd
function accum(s) {
// your code
return s.split('').map((e,i) => e.toUpperCase() + e.toLowerCase().repeat(i)).join('-')
}
///
function accum(s) {
var arr = s.split("")
var arrStr = []
arr.forEach((item, index) => {
var str = ""
item = item.toLowerCase()
for (var i = 0; i < index + 1; i++) {
str = str + item
}
str = str.charAt(0).toUpperCase() + str.slice(1)
arrStr.push(str)
})
return arrStr.join("-")
}