1.反转
输入'123'
输出'321'
输入'abcdefg'
输入'gfedcba'
//反转的两种写法及时间比较
function reverse1(input) {
if (typeof input !== 'string') {
throw new Error('给我字符串啊')
}
var output = ''
for (var i = 0; i < input.length; i++) {
output = input[i] + output
}
return output
}
function reverse2(input) {
if (typeof input !== 'string') {
throw new Error('我只要字符串')
}
return input.split('').reverse().join('')
}
var t1 = new Date() for (var i = 0; i < 100000; i++) {
reverse1('sakjdlaskjdlaskjdaslkjdaslkjdaslkfjaslkfjaslf;kj')
}
console.log(new Date() - t1) var t2 = new Date() for (var i = 0; i < 100000; i++) {
reverse2('sakjdlaskjdlaskjdaslkjdaslkjdaslkfjaslkfjaslf;kj')
}
console.log(new Date() - t2)
2.加横线
输入'123456789'
输出'123-456-789-'
2.1遍历
function x(input){
var output = ''
for(var i=0;i<input.length;i++){
output = output + input[i]
if((i%3===2)&& i!==input.length-1){
output = output + '-'
}
}
return output
}
console.log(x('123456673'))
2.2正则
function x(input){
var string = input.replace(/.{3}/g, function(三个数字){return 三个数字 + "-"})
if(string.lastIndexOf('-')===string.length - 1){
string = string.substring(0,string.length-1)
}
return string
}
console.log(x('123456673'))
2。3(扩展需求):反向、横线
输入'abcd'
输出'd-cba'
function xx(input){
var output = ''
for(var i=0;i<input.length;i++){
output = input[i] + output
if((input.length-i)%3 === 0 && i!=0){
output = '-'+output
}
}
return output
}
xx('abcd567890')
3.数组去重
输入[1,2,2,2,2,3,4,4]
输出[1,2,3,4]
//前端一定要学习排序算法!!
8种排序算法
1.冒泡
2.选择
3.插入
4.快排
5.堆排
6.桶排(扑克牌分堆算法)
7.归并
8.基数排序
3.1桶排序
//桶排缺点,会把所有都变成字符串,分不出数字和字符串的区别
function unique(array){
var newArray = []
var hash = {}
for (var i=0;i<array.length;i++){
var number = array[i]
if(number in hash){
}else{
hash[number] = '方方'
}
}
for(var key in hash){
newArray.push(parseInt(key,10))
}
return newArray
}
console.log(unique([1,2,3,4,5,4,3,32,1,1,2]))
3.2ES6 中 set api
使用ES6 中 set api 好处,能识别数字和字符串 缺点:IE不支持
function unique(array){
var set = new Set(array)
var newArray = Array.from(set)
return newArray
}
console.log(unique([1,2,3,4,5,4,3,32,1,1,2]))
3.3
//underscore.js