首頁 > web前端 > js教程 > 主體

JS數組、字串及數學函數

jacklove
發布: 2018-05-21 11:55:55
原創
1331 人瀏覽過

本篇將會對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]      # ##[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(&#39;<dl class="product">&#39;);
  arrey.push("<dt>"+new1+"</dt>");  for(var i =0;i<new2.length;i++){
  arrey.push("<dd>"+new2[i]+"</dd>")
  }
  arrey.push(&#39;</dl>&#39;);  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]===&#39;number&#39;){
      arre.push(arr[i])
      }
  }  console.log(arre);
}
filterNumeric(arr)  //[1, 3, 5, 2]
登入後複製

物件obj有個className屬性,裡面的值為的是空格分割的字串(和html元素的class特性類似),寫addClass、removeClass函數,有以下功能:

var obj = {  className: &#39;open menu&#39;};  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, &#39;new&#39;);          //Object {className: "open menu new"}addClass(obj, &#39;open&#39;);        //因为open已经存在,此操作无任何办法addClass(obj, &#39;me&#39;);           // 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(&#39; &#39;);  console.log(obj);
}
removeClass(obj,"open");        //Object {className: "menu new me"}removeClass(obj, &#39;blabla&#39;);    //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(&#39;hello hunger valley&#39;)) } );
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] !== &#39;number&#39;){
      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 === &#39;number&#39;; 
}
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.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!