首页 >web前端 >js教程 > 正文

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

原创2018-05-21 11:55:550549
本篇将会对js数组和字符串以及函数进行讲解。

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

push:在数组最后添加一个元素,语法是数组.push (所要添加的元素);,返回值为数组长度

pop: 删除数组最后一个元素,语法为数组.pop( );返回值为删除的元素名称

shift:删除数组第一个元素,语法为数组.shift( );返回值为删除的元素名称

unshift:在数组首位添加一个元素,后面元素向后偏移,语法为数组.unshift (所要添加的元素);,返回值为数组长度

join:将数组连接为字符串,不修改原本的数组,语法为数组.join(),返回值为连接完成的字符串

split: 将字符串分隔并变为数组,不修改原本的字符串,语法为字符串.split('分隔符');

代码:

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

splice实现push:

new1
[91, 3, 2, 1, 34, 5] //new1数组的元素new1.splice(new1.length,0,91) //new1.length代表数组最后一位后面,0为关键字添加,91为所要添加元素[]

new1
[91, 3, 2, 1, 34, 5, 91] //成功在数组new1最后添加元素91

用splice实现pop:

new1
[91, 3, 2, 1, 34, 5, 9, 91] //new1数组的元素new1.splice(new1.length-1,1) //new1.length代表数组最后一位,1为长度[91]

new1
[91, 3, 2, 1, 34, 5, 9] //成功删除最后一位元素91

splice实现shift:

new1
[91, 3, 2, 1, 34, 5, 645] //new1数组的元素new1.splice(0,1) //0代表数组下标索引数,1代表删除个数[91] //返回删除的元素new1
[3, 2, 1, 34, 5, 645] //成功删除new1数组第一个元素

splice实现unshift:

new1
[3, 2, 1, 34, 5, 645] //new1数组的元素new1.splice(0,0,91) //第一个0代表数组下标索引数,第二个0为关键字添加,91为所要添加的元素[]

new1
[91, 3, 2, 1, 34, 5, 645] //成功在数组第一位添加元素91

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

var prod = {    name: '女装',    styles: ['短款', '冬季', '春装']
};function getTp(data){  var new1  = prod.name;  var new2  = prod.styles;  var arrey =[];
  arrey.push('<dl class="product">');
  arrey.push("<dt>"+new1+"</dt>");  for(var i =0;i<new2.length;i++){
  arrey.push("<dd>"+new2[i]+"</dd>")
  }
  arrey.push('</dl>');  console.log(arrey.join());  
}
getTp(prod)//<dl class="product">,<dt>女装</dt>,<dd>短款</dd>,<dd>冬季</dd>,<dd>春装</dd>,</dl>

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

var arr = [ "test" , 2 , 1.5 , false ]function find(arr,add){  for(var i = 0;i < arr.length; i++){    if(add==arr[i] && add !== 0){      return console.log(i)
    }
  }  console.log(-1)
}
find(arr, "test") // 0find(arr, 2) // 1find(arr, 0) // -1

写一个函数filterNumeric,实现如下功能

arr = ["a", 1,3,5, "b", 2];var arre = [];function filterNumeric(arr){  for(var i= 0; i< arr.length;i++){      if(typeof arr[i]==='number'){
      arre.push(arr[i])
      }
  }  console.log(arre);
}
filterNumeric(arr)  //[1, 3, 5, 2]

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

var obj = {  className: 'open menu'};  var shu = obj.className.split(" ");     
function addClass(obj,nano){                
  for(var i = 0;i< shu.length; i++) {        
    if(shu[i] === nano) {              
      return console.log("因为"+nano+"已经存在,此操作无任何办法");
    }                             
  }
  shu.push(nano);                   
 //console.log(shu);
  obj.className = shu.join(" ");   console.log(obj);
} 
addClass(obj, 'new');          //Object {className: "open menu new"}addClass(obj, 'open');        //因为open已经存在,此操作无任何办法addClass(obj, 'me');           // Object {className: "open menu new me"}console.log(obj.className);    // open menu new mefunction removeClass(obj,habo){  //console.log(shu)
  for(var i = 0;i<shu.length;i++){    if(shu[i] === habo) {
      shu.splice(i,1);
    }
  }
  obj.className = shu.join(' ');  console.log(obj);
}
removeClass(obj,"open");        //Object {className: "menu new me"}removeClass(obj, 'blabla');    //Object {className: "menu new me"}

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

function camelize(lama){  var lala = lama.split("-");  //["list", "style", "image"]
  var a =[lala[0]];  for(var i =1; i<lala.length; i++) {    var num =lala[i][0].toUpperCase();        //"S",    "I"
    var b = lala[i].replace(lala[i][0],num)
    a.push(b)  
  }console.log(a.join(""))
}
camelize("background-color")   //"backgroundColor"camelize("list-style-image")    //"listStyleImage""

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

arr = ["a", "b"];  
arr.push( function() { alert(console.log('hello hunger valley')) } );
arr[arr.length-1]()  //

输出的是function函数的内容'hello hunger valley'并弹出窗口显示underfined。因为第二段直接将整个函数添加到数组arr后面成为它最后一个元素,最后一句代表将arr数组的最后一个元素执行调用,console.log执行完会销毁,所以打印结果为'hello hunger valley',而弹窗结果为underfined

写一个函数filterNumericInPlace,过滤数组中的数字,删除非数字

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

写一个ageSort函数实现如下功能

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(data){
  data.sort(function (a,b){    return a.age-b.age;
  })  console.log(data);
}
ageSort(people); // [ bob, mary, john ]

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

function isNumeric (el){    return typeof el === 'number'; 
}
arr = ["a",3,4,true, -1, 2, "b"];function filter(arr, func){  
  for(var i =0;i<arr.length;i++){    if(!func(arr[i])){
      arr.splice(i,1);
    }
  }  return arr;
}
arr = filter(arr, isNumeric) ;console.log(arr);
arr = filter(arr,function(val){ return val > 0});console.log(arr); 
[3, 4, -1, 2]
[3, 4, 2]

字符串

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

function ucFirst(daho){  var add= daho[0].toUpperCase();
  daho=daho.replace(daho[0],add)  console.log(daho);
}
ucFirst("hunger")"Hunger"

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

function truncate(str, maxlength){  if(str.length-1>maxlength){
    add = str.substr(0,maxlength);    console.log(add+"...");
  }else{    return console.log(str);
  }
}
truncate("hello, this is hunger valley,", 10)
truncate("hello world", 20)"hello, thi...""hello world"

数学函数

写一个函数limit2,保留数字小数点后两位,四舍五入, 如:

var num1 = 3.456;function limit2(num){
  num=Math.round(num*100)/100;  console.log(num);
}
limit2(num1)
limit2(2.42)3.462.42

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

function habo(min,max){   console.log(Math.random()*(min-max)+max)
 }
 habo(5,15)

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

function habo(min,max){
  add = Math.random()*(min-max)+max;  console.log(Math.round(add));  
 }
 habo(5,12)

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

function damo(len,min,max){
  arr=[];
  len == arr.length;  for(var i =0;i<len;i++){
    arr.push(Math.round(Math.random()*(min-max)+max));
  }  console.log(arr)
}
damo(5,18,70)
[53, 34, 43, 43, 33]

本篇对JS数组、字符串及数学函数相关内容进行了讲解,更多相关知识请关注php中文网。

相关推荐:

关于JS时间对象和递归问题

一些CSS样式基础知识

关于JS定时器和闭包问题的讲解

以上就是JS数组、字符串及数学函数的详细内容,更多请关注php中文网其它相关文章!

php中文网最新课程二维码

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

  • 相关标签:javascript 字符串 函数
  • 相关文章

    相关视频


    网友评论

    文明上网理性发言,请遵守 新闻评论服务协议

    我要评论
  • 专题推荐

    推荐视频教程
  • javascript初级视频教程javascript初级视频教程
  • jquery 基础视频教程jquery 基础视频教程
  • 视频教程分类