1.使用js 数组去重复:
方法①:
var arr=[1,2,1,5,2,3,5,1,6,9]; function deRepeat(){ var newArray=[]; var obj={}; var index=0; var len=arr.length; for(var i=0;i<len;i++){ if(obj[arr[i]]==undefined){//不存在 obj[arr[i]]=1; newArray[index++]=arr[i]; }else if(obj[arr[i]]==1) continue; } return newArray; } alert(deRepeat(arr));
运行结果:
方法②:
var arr=[1,2,1,5,2,3,5,1,6,9]; for(var i=0,obj={},newArray=[],len=arr.length;i<len;i++){ if(!obj[arr[i]]){ obj[arr[i]]=1; newArray.push(arr[i]) } } alert(newArray)
运行结果:
2.js的继承及原型属性,扩展内置数据类型的方法。(比如:给String对象定义一个repeatify方法:该方法接收一个整数参数,作为字符串重复的次数,最后返回重复指定次数的字符串。)
String.prototype.repeatify = String.prototype.repeatify || function(times) { var str = ''; for (var i = 0; i < times; i++) { str += this; } return str; }; console.log('hello'.repeatify(3));
运行结果:
//hellohellohello
3.题目:a与b比较大小,若a大于b,返回true
function compareSequence(a, b){ //如果是字符串的数字( "555" < "223" )的处理 var num1 = parseInt(a), num2 = parseInt(b); if (typeof(num1) === "number" && typeof(num2) === "number") { if (num1 > num2) { return true; } else { return false; } } } console.log(compareSequence(555,223));
运行结果:
true
4.题目:将一组单词存储在一个数组中,并按正序和倒序分别显示这些单词
var arr=["This","is","a","pen"], len=arr.length, i=0, j=len-1; for(;i<len;i++){//正序 console.log(arr[i]); } for(;j>=0;j--){//倒序 console.log(arr[j]); }
运行结果:
This is
a pen pen a is This