美文网首页
JS数组、字符串、数学函数

JS数组、字符串、数学函数

作者: 泰格_R | 来源:发表于2016-09-19 15:15 被阅读25次

1.数组方法里push、pop、shift、unshift、join、split分别是什么作用。

push:栈方法,先入后出,向栈顶增加一个元素,返回新数组长度。
pop:栈方法,先入后出,从栈顶删除一个元素,返回被删除的元素。
shift:队列方法,先入先出,从队列首部删除一个元素,返回被删除的元素。
unshift:队列方法,先入先出,从队列首部增加一个元素,返回新数组长度。
join:将数组中的元素以join指定参数为连接符连接。
split:将字符串以指定参数为分隔符分割成数组,指定的参数一定是原字符串中存在的。


2.用 splice 实现 push、pop、shift、unshift方法

var arr=[0,1,2,3,4,5,6,7,8,9];
arr.splice(arr.length,0,10); //splice实现push
arr.splice(arr.length-1,1); //splice实现pop
arr.splice(0,1,-1); //splice实现shift,删除首元素
arr.splice(0,0); //splice实现unshift,增加一个元素到队首

3.使用数组拼接出如下字符串

var prod = {
    name: '女装',
    styles: ['短款', '冬季', '春装']
};
function getTpl(data){
//todo...
};
/*
 getTpl(prod) //调用函数输出如下内容
<dl class="product"> 
<dt>女装</dt> 
<dd>短款</dd> 
<dd>冬季</dd> 
<dd>春装</dd>
</dl>
*/
function getTpl(data){
var htmlarr=[];//创建空数组存放html元素;
htmlarr.push('<dl class="product"> ');//栈顶增加新html元素
htmlarr.push('<dt>'+data.name+'</dt> ');//栈顶增加新html元素
data.styles.map(function(e,i,a){//styles数组中的每个元素使用回调函数创建html元素
htmlarr.push('<dd>'+e+'</dd> ');
})
htmlarr.push('</dl>');
console.log(htmlarr.join(""));//htmlarr数组中用""连接起来
};
getTpl(prod);//调用函数

4.写一个find函数,实现下面的功能

var arr = [ "test", 2, 1.5, false ]
find(arr, "test") // 0
find(arr, 2) // 1
find(arr, 0) // -1

代码如下:

function find(arr,num){
return arr.indexOf(num);
};


5.写一个函数filterNumeric,把数组 arr 中的数字过滤出来赋值给新数组newarr, 原数组arr不变

arr = ["a", "b", 1, 3, 5, "b", 2];
newarr = filterNumeric(arr);  //   [1,3,5,2]

代码如下:

var arr = ["a", "b", 1, 3, 5, "b", 2];
        function filterNumberic(el){
        var newarr;
        return newarr=arr.filter(function(e){//filter方法返回满足特定条件的元素组成的数组
        return typeof(e)==="number";
        })
      };
     filterNumberic(arr);
}

6.对象obj有个className属性,里面的值为的是空格分割的字符串(和html元素的class特性类似),写addClass、removeClass函数,有如下功能:

var obj = {
  className: 'open menu'
}
addClass(obj, 'new') // obj.className='open menu new'
addClass(obj, 'open')  // 因为open已经存在,所以不会再次添加open
addClass(obj, 'me') // me不存在,所以 obj.className变为'open menu new me'
console.log(obj.className)  // "open menu new me"

removeClass(obj, 'open') // 去掉obj.className里面的 open,变成'menu new me'
removeClass(obj, 'blabla')  // 因为blabla不存在,所以此操作无任何影响

代码如下:

var obj = {
  className: 'open menu'
      };

function addClass(obj,newstr){    //addClass函数
        var newarr;
        newarr=obj.className.split(" ");
        if(newarr.indexOf(newstr)<0){
          newarr.splice(newarr.length,0,newstr);
          obj.className=newarr.join(" ");
          return obj.className;
        }
        else{
          return obj.className;
        }
      }
addClass(obj, 'new') // obj.className='open menu new'
addClass(obj, 'open')  // 因为open已经存在,所以不会再次添加open
addClass(obj, 'me') // me不存在,所以 obj.className变为'open menu new me'
console.log(obj.className)  // "open menu new me"

function removeClass(obj,newstr){   //removeClass函数
    var newarr;
    newarr=obj.className.split(" ");
    if(newarr.indexOf(newstr)>=0){
      newarr.splice(newarr.indexOf(newstr),1);
      obj.className=newarr.join(" ");
      return obj.className;
    }
    else{
      return obj.className;
    }
  }
removeClass(obj, 'open') // 去掉obj.className里面的 open,变成'menu new me'
removeClass(obj, 'blabla')  // 因为blabla不存在,所以此操作无任何影响

7.写一个camelize函数,把my-short-string形式的字符串转化成myShortString形式的字符串

camelize("background-color") == 'backgroundColor'
camelize("list-style-image") == 'listStyleImage'

代码如下:

function camelize(str){
  return str.split("-").join("");  //先分割开再用join连接起来
}

8.如下代码输出什么?为什么?

arr = ["a", "b"];
arr.push( function() { alert(console.log('hello hunger valley')) } );//输出结果3,arr数组中增加了一个元素function(){}
arr[arr.length-1]()  // 返回结果先弹出alert:undefined,再输出数组中索引号为2的元素,即function(){}。'hello hunger valley'

9.写一个函数filterNumericInPlace,过滤数组中的数字,删除非数字。要求在原数组上操作

arr = ["a", "b", 1, 3, 4, 5, "b", 2];
//对原数组进行操作,不需要返回值
filterNumericInPlace(arr);
console.log(arr)  // [1,3,4,5,2]

代码如下:

arr = ["a", "b", 1, 3, 4, 5, "b", 2];
function filterNumbericInplace(arr){
  for(var i=0;i<arr.length;i++){
    if(typeof(arr[i])!=="number"){
      arr.splice(i,1);
      i--;
    }
  }
}
filterNumericInPlace(arr);
console.log(arr)  // [1,3,4,5,2]



10.写一个ageSort函数实现数组中对象按age从小到大排序

var john = { name: "John Smith", age: 23 };
var mary = { name: "Mary Key", age: 18 };
var bob = { name: "Bob-small", age: 6 };
var people = [ john, mary, bob ];
 function ageSort(people){
      people.sort(function(a,b){
        return a.age-b.age;
      })
 }
console.log(people)//输出结果如下:
/*[Object, Object, Object]
0:Object
age:6
name:"Bob-small"
__proto__:Object

1:Object
age:18
name:"Mary Key"
__proto__:Object

2:Object
age:23
name:"John Smith"
__proto__:Object

length:3
__proto__:Array[0]
*/

11.写一个filter(arr, func) 函数用于过滤数组,接受两个参数,第一个是要处理的数组,第二个参数是回调函数(回调函数遍历接受每一个数组元素,当函数返回true时保留该元素,否则删除该元素)。实现如下功能

arr = ["a",3,4,true, -1, 2, "b"]
arr = filter(arr, isNumeric) ; // arr = [3,4,-1, 2], 过滤出数字
arr = filter(arr, isInt);//arr=[3,4,2]

代码如下:

//构造回调函数从数组中筛选出数字、为正数的数字
//构造函数筛选出数字
arr = ["a",3,4,true, -1, 2, "b"];

function isNumeric(el){
  if(typeof(el)==="number"){
    return el;
  }
}

function filter(arr,isNumeric){
  var newarr=arr.filter(isNumeric);
  return newarr;
}
filter(arr,isNumeric)//输出结果[3,4,-1,2]



//构造函数筛选出数字,且数字是正数
arr = ["a",3,4,true, -1, 2, "b"];

function isInt(el){
  if(typeof(el)==="number" && el>=0){
    return el
  }
}

function filter(arr,isInt){
  var newarr2=arr.filter(isInt);
  return newarr2;
}

filter(arr,isInt)//输出结果[3,4,2]

12.写一个 ucFirst函数,返回第一个字母为大写的字符.

//实现  ucFirst("hunger") == "Hunger"
function ucFirst(el){
  var newstring=el[0].toUpperCase()+el.substring(1)
  return newstring;
}
ucFirst("hunger") 
//返回结果为 "Hunger"

13.写一个函数truncate(str, maxlength), 如果str的长度大于maxlength,会把str截断到maxlength长,并加上...,如下

truncate("hello, this is hunger valley,", 10)) == "hello, thi...";
truncate("hello world", 20)) == "hello world"

代码如下:

function truncate(str,maxlength){
  if(str.length>maxlength){
    return str.substring(0,maxlength)+"...";
  } else{
    return str.substring(0,maxlength);
  }
}
truncate("hello, this is hunger valley,", 10));//返回"hello, thi..."
truncate("hello world", 20))//返回"hello world"

14.写一个函数,获取从min到max之间的随机整数,包括min不包括max

function randomnum1(el1,el2){
  return Math.floor(Math.random()*(el2-el1)+el1);//向下取整数
}

15.写一个函数,获取从min都max之间的随机整数,包括min包括max

function randomnum2(el1,el2){
  return Math.floor(Math.random()*(el2-el1+1)+el1)
}

16.写一个函数,获取一个随机数组,数组中元素为长度为len,最小值为min,最大值为max(包括)的随机整数

function randomnum3(len,min,max){
  var newarr=[];
  for(var i=0;i<len;i++){
    newarr[i]=Math.floor(Math.random()*(max-min+1)+min)
  }
  return newarr
}

17.写一个函数,生成一个长度为 n 的随机字符串,字符串字符的取值范围包括0到9,a到 z,A到Z

function getRandStr(len){
  var str="0123456789abcdefthijklmnopqrstuvwxyzABCDEFTHIJKLMNOPQRSTUVWXYZ"
  var newstr=[];
  for(var i=0;i<len;i++){
    newstr[i]=str[Math.floor(Math.random()*(str.length+1))]
  }
  return newstr.join("");
}
var str = getRandStr(3);

相关文章

网友评论

      本文标题:JS数组、字符串、数学函数

      本文链接:https://www.haomeiwen.com/subject/owhwettx.html