JS习题
1.使用js内置对象date计算你来到这个世界多少天了
function Day() {
var now = new Date();
var date = new Date(2001,02,02);
var res = parseInt((now.getTime() - date.getTime()) / (24 * 60 * 60 * 1000));
console.log("您来到这个世界"+res+"天了!");
}
Day();
2.判断一个字符在另一个字符中出现的次数
字符
var string = "helloworldhelloworldhelloworld";
var s1 = string.split("");
var s = "l";
var count = 0;
for (var i = 0; i < string.length; i++) {
if (s == s1[i]) {
count += 1;
}
}
console.log("字符的个数为:"+count);
字符串
var str1="helloworldhelloworldhelloworldllo";
var str2="llo";
var index=-1;//-1不存在
var count1=0;
var fromIndex=0;
while((index=str1.indexOf(str2,fromIndex))!=-1){
count1++;
fromIndex=index+str2.length;
}
console.log(count1);
3.反转字符串 s= “12345” -- > “54321”
function printString() {
var s = "12345";
var s1 = s.split("");
var str = "";
for (var i = s.length - 1; i >= 0; i--) {
str += s1[i];
// str+=s.charAt(i);// 方法二
}
console.log(str);
}
printString();
4.反转数组[1,2,3,4,5] à [5,4,3,2,1]
var arr = [1, 2, 3, 4, 5];
for(var left=0,right=arr.length-1;left<right;left++,right--){
var temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
}
function printArr(arr) {
var str = "[";
for (var i = 0; i < arr.length; i++) {
if (i != arr.length - 1) {
str += arr[i] + ",";
} else {
str += arr[i] + "]";
}
}
console.log(str);
}
printArr(arr);
5.声明一个长度为10的数组,随机地为数组的元素赋值(2位整数)
var arr = new Array(10);
for (var i = 0; i < arr.length; i++) {
var a = parseInt(Math.random() * 90 + 10);
arr[i] = a;
console.log("第" + (i + 1) + "位:" + arr[i]);
}