字符串逆序输出
-
数组的reverse()函数
function reverserString1(str){ return str.split('').reverse().join('') } -
字符串的charAt()函数,从尾部开始遍历
function reverseString2(str){ let result = '' for(let i = str.length - 1; i >= 0; i--) { result += str.charAt(i) } return result } -
递归
// 这个函数还需要做一些边界判断 function reverseString3(str, position, result){ if(position < 0) return result result += str.charAt(position--) return reverseString3(str, position, result) } -
通过call()函数来改变slice()函数的执行主体
function reverseString4(str){ const arr = Array.prototype.slice.call(str) return arr.reverse().join('') } -
借助栈的先进后出原则
function Stack() { this.data = [] this.top = 0 } Stack.prototype = { // 入栈 push: function push(element) { this.data[this.top++] = element }, // 出栈 pop: function pop() { return this.data[--this.top] }, length: function() { return this.top } } function reverseString5(str) { const s = new Stack() const arr = str.split('') let result = '' arr.map(item => s.push(item)) arr.map((_, index) => result+= s.pop(index)) return result }
统计字符串中出现次数最多的字符及出现的次数
- 对象