1. 不借助临时变量,进行两个整数的交换
function swap(a,b){
b = b - a;
a = a + b;
b = a - b;
return [a, b];
}
原理:a = a + (b - a)
2. 找出下列正数组中的最大差值:[10, 5, 11, 4, 9]
function getMaxProfit(arr){
var minValue = maxValue = arr[0];
var maxProfit = 0;
for(var i = 0; i < arr.length; i++){
var currentValue = arr[i];
minValue = Math.min(minValue, currentValue);
maxValue = Math.max(maxValue, currentValue);
}
maxProfit = maxValue - minValue;
return maxProfit;
}
3. 随机生成指定长度的字符串
function randomString(n){
var str = get26Letters();
var tmp = '', i = 0 ;
for(i = 0; i < n; i++){
tmp += str.charAt(Math.floor(Math.random() * str.length));
}
return tmp;
}
function get26Letters(){
var str = '';
for(var i = 0; i < 26; i++){
str += String.fromCharCode(97+i);
}
return str;
}
4. 实现类似 getElementsByClassName 的功能
/* function queryClassName(node, name){
var starts = '(^|[\n\r\t\f])', ends = '([\n\r\t\f]|$)';
var array = [], regex = new RegExp(starts + name + ends),
elements = node.getElementsByTagName('*'),
length = elements.length, i = 0 , element;
while( i < length ){
element = elements[i];
if(regex.test(element.className)){
array.push(element);
}
i += 1;
}
return array;
}
*/
网友评论