标签:
tips javascript(一)
实现type函数用于识别标准类型和内置对象类型,语法如下: var t = type(obj);
function type(o){
if (o === null)
return ‘null‘;
if (typeof o !== ‘object‘)
return typeof o;
if (o instanceof Number)
return ‘number‘
if (o instanceof String)
return ‘string‘
if (o instanceof Date)
return ‘date‘;
if (o instanceof Array)
return ‘array‘;
if (o instanceof RegExp)
return ‘regexp‘;
return ‘object‘;
}
已知一数组,如何筛选出该数组中小于该数组平均数的值,并存入另一个数组
var arr = [1, 11, 33, 44, 55, 2, 11, 1, 1, 1];
//计算数组的平均值
var sum = 0;
for(var i=0,il=arr.length;i<il;i++){
sum = sum + arr[i];
}
console.log(sum);
sum = sum / il;
console.log(sum);
//取出不同的值
var newArr1 = [] , str = {};
for(var i=0,il=arr.length;i<il;i++){
var item = arr[i];
var key = typeof(item) + item;
// console.log(key);
if(str[key] !== 1){
newArr1.push(item);
str[key] = 1;
}
}
var arr1 = newArr1;
console.log(arr1);
//将小于平均数的值取出来,赋值给一个新数组
var newArr2 = [];
for(var i=0,il=arr1.length;i<il;i++){
if(arr[i]<sum){
newArr2.push(arr[i]);
}
}
console.log(newArr2);
//用冒泡排序方法对数组进行排序
for(var i=0,il=newArr2.length;i<il;i++){
for(var j=0,jl=newArr2.length;j<jl;j++){
if(newArr2[i]<newArr2[j]){
var temp = newArr2[i];
newArr2[i] = newArr2[j];
newArr2[j] = temp;
}
}
}
console.log(newArr2);
标签:
原文地址:http://www.cnblogs.com/foodoir/p/5843351.html