Home > Web Front-end > JS Tutorial > body text

JS arrays, strings and mathematical functions

jacklove
Release: 2018-05-21 11:55:55
Original
1376 people have browsed it

This article will explain js arrays, strings and functions.

What are the functions of push, pop, shift, unshift, join, and split in the array method?

push: Add an element at the end of the array, the syntax is array.push (the element to be added) ;, the return value is the length of the array

pop: delete the last element of the array, the syntax is array.pop( ); the return value is the name of the deleted element

shift: delete the first element of the array , the syntax is array.shift(); the return value is the name of the deleted element

unshift: add an element at the beginning of the array, and the subsequent elements are offset backwards, the syntax is array.unshift (the element to be added); , the return value is the length of the array

join: Connect the array into a string, without modifying the original array, the syntax is array.join(), the return value is the string after the connection is completed

split : Separate the string and turn it into an array without modifying the original string. The syntax is string.split('separator');

Code:

Use splice to implement push and pop , shift, unshift method

splice implements push:

new1
[91, 3, 2, 1, 34, 5] //Element of new1 array new1.splice(new1. length,0,91) //new1.length represents after the last digit of the array, 0 is the keyword to add, 91 is the element to be added []

new1
[91, 3, 2, 1, 34, 5, 91] //Successfully added element 91 at the end of array new1

Use splice to implement pop:

new1
[91, 3, 2, 1, 34 , 5, 9, 91] //Element of new1 array new1.splice(new1.length-1,1) //new1.length represents the last digit of the array, 1 is the length [91]

new1
[91, 3, 2, 1, 34, 5, 9] //Successfully delete the last element 91

splice implements shift:

new1                                    
[ 91, 3, 2, 1, 34, 5, 645] //Elements of new1 array new1.splice(0,1) //0 represents the array subscript index number, 1 represents the number of deletions [91] //Return to delete Element new1 ##[3, 2, 1, 34, 5, 645] //Elements of new1 array new1.splice(0,0,91) //The first 0 represents the array subscript index number, and the second 0 is the key Word addition, 91 is the element to be added []

new1

[91, 3, 2, 1, 34, 5, 645] //Successfully added element 91

at the first position of the array

Use an array to splice the following string

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>
Copy after login

Write a find function to implement the following functions
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
Copy after login

Write a function filterNumeric to implement the following functions
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]
Copy after login

The object obj has a className attribute, and the value inside is a space-delimited string (similar to the class attribute of the html element). Write the addClass and removeClass functions, which have the following functions:

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"}
Copy after login

Write a camelize function , convert the string in the form of my-short-string into the string in the form of 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""
Copy after login

What does the following code output? Why?

arr = ["a", "b"];  
arr.push( function() { alert(console.log(&#39;hello hunger valley&#39;)) } );
arr[arr.length-1]()  //
Copy after login

The output is the content of the function function 'hello hunger valley' and the pop-up window displays underfined. Because the second paragraph directly adds the entire function to the back of the array arr to become its last element, and the last sentence means to execute the call on the last element of the arr array, console.log will be destroyed after execution, so the printed result is 'hello hunger valley', The result of the pop-up window is underfined

Write a function filterNumericInPlace to filter the numbers in the array and delete non-digits

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);
Copy after login

Write an ageSort function to implement the following functions

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 ]
Copy after login

Write a filter The (arr, func) function is used to filter arrays and accepts two parameters. The first is the array to be processed, and the second parameter is the callback function (the callback function traverses and accepts each array element, and retains the element when the function returns true , otherwise delete the element)

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]
Copy after login

String

Write a ucFirst function to return the character whose first letter is uppercase

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

Write a function truncate(str, maxlength ), if the length of str is greater than maxlength, str will be truncated to maxlength and added..., such as

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"
Copy after login

Mathematical function

Write a function limit2, retaining two digits after the decimal point bit, rounded, such as:

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

Write a function to get the random number between min and max, including min but excluding max

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

Write a function to get the random number between min and max Random integers between, including min and max

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

Write a function to obtain a random array. The elements in the array are random numbers with length len, minimum value min, and maximum value max (inclusive)

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]
Copy after login

This article explains the content related to JS arrays, strings and mathematical functions. For more related knowledge, please pay attention to the PHP Chinese website.

Related recommendations:

About JS time objects and recursion issues

Some basic knowledge of CSS styles

Explanation on JS timer and closure issues

The above is the detailed content of JS arrays, strings and mathematical functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!