Home Web Front-end HTML Tutorial JavaScript Array-String-Math Function

JavaScript Array-String-Math Function

Mar 08, 2018 pm 03:24 PM
javascript js string

This time I will bring you JavaScript array-string-mathematical function, What are the precautions for using JavaScriptarray-string-mathematical function , the following is a practical case, let’s take a look.

What are the functions of push, pop, shift, unshift, join, and split in array methods.

The push() method adds one or more elements to the end of the array and returns the new length of the array (length attribute value).
The pop() method deletes the last element in an array and returns this element.
The shift() method deletes the first element of the array and returns this element. This method changes the length of the array.
The unshift() method adds one or more elements to the beginning of the array and returns the new length value of the array.
The join() method concatenates all elements in the array into a string.
**split() **The method splits a String object into a string array by splitting the string into substrings.

Code question

Array

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

Definition and usage
splice() method is used for insertion and deletion Or replace elements of an array.
Syntax

arrayObject.splice(index,howmany,element1,.....,elementX)
Copy after login

Parameter description

index Required. Specifies where to add/remove elements. This parameter is the index of the array element to start inserting and/or deleting, and must be a number.
howmany Required. Specifies how many elements should be removed. Must be a number, but can be "0". If this parameter is not specified, all elements starting from index to the end of the original array are deleted. element1 optional. Specifies the new element to be added to the array. Insertion begins at the index pointed to by index.
elementX Optional. Several elements can be added to the array.
Return value
If an element is deleted from arrayObject, the array containing the deleted element is returned.

splice->push
var a = [1,2,3,4,5]
var b = [1,2,3,4,5]
console.log(a);
console.log(b);
a.push(6);
b.splice(5,1,6);
console.log(a);
console.log(b);
splice->pop
var a = [1,2,3,4,5]
var b = [1,2,3,4,5]
console.log(a);
console.log(b);
a.pop();
b.splice(4,1);
console.log(a);
console.log(b);
splice->shift
var a = [1,2,3,4,5]
var b = [1,2,3,4,5]
console.log(a);
console.log(b);
a.shift();
b.splice(0,1);
console.log(a);
console.log(b);
splice->unshift
var a = [1,2,3,4,5]
var b = [1,2,3,4,5]
console.log(a);
console.log(b);
a.unshift(-1);
b.splice(0,0,-1);
console.log(a);
console.log(b);
Copy after login

Use an array to splice the following string

var prod = {    name: '女装',    styles: ['短款', '冬季', '春装']
};function getTpl(data){//todo...};var result = getTplStr(prod);  //result为下面的字符串
    <dl class="product">
        <dt>女装</dt>
        <dd>短款</dd>
        <dd>冬季</dd>
        <dd>春装</dd>
    </dl>
Copy after login

Code:


var prod = {
name: &#39;女装&#39;,
styles: [&#39;短款&#39;, &#39;冬季&#39;, &#39;春装&#39;]
};
function getTplStr(data){
var htmls = [];
htmls.push(&#39;<dl class="product">&#39;,&#39;<dt>&#39;+data,name+&#39;<dt>&#39;);
for(i=0;i<data.styles.length;i++){
htmls.push(&#39;<dd>&#39;+data.styles[i]+&#39;<dd>&#39;)
}
htmls.push(&#39;<dl>&#39;);
var htmls = htmls.join(&#39;&#39;)
return htmls
};
var result = getTplStr(prod);  //result为下面的字符串
console.log(result)
Copy after login

Write a find function to achieve the following functions


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

Code:


var arr = [ "test", 2, 1.5, false ]
var find = function(a,b){
console.log(a.indexOf(b))
}
find(arr, "test") // 0
find(arr, 2) // 1
find(arr, 0) // -1
Copy after login

Write a function filterNumeric to implement the following functions


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

Code:

Method 1:

arr = ["a", 1,3,5, "b", 2];
var filterNumberic = function(data){
var a = [];
for(i=0;i<data.length;i++){
if(typeof data[i] === &#39;number&#39;){
a.push(data[i]);
}
}
return a
}
Copy after login

newarr = filterNumberic(arr); // [1,3,5,2]

console.log(newarr)
Method 2:

arr = ["a", 1,3,5, "b", 2];
function isNumber(element) {
return typeof element === &#39;number&#39;;
}
var newarr = arr.filter(isNumber)
console.log(newarr)
Copy after login

Object obj has The className attribute, 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;}addClass(obj, &#39;new&#39;) // obj.className=&#39;open menu new&#39;addClass(obj, &#39;open&#39;)  // 因为open已经存在,此操作无任何办法addClass(obj, &#39;me&#39;) // obj.className=&#39;open menu new me&#39;console.log(obj.className)  // "open menu new me"
 removeClass(obj, &#39;open&#39;) // obj.className=&#39;menu new me&#39;  removeClass(obj, &#39;blabla&#39;)  // 不变
Copy after login

Code:


var obj = {className: &#39;open menu&#39;}var addClass = function(a,b){var name = a.className.split(" ");if(name.indexOf(b) === -1) {name.push(b);}else{console.log("因为"+b+"已经存在,此操作无任何办法");}a.className = name.join(" ");console.log(&#39;obj.className=&#39;+a.className);}var removeClass = function(a,b){var name = a.className.split(" ");if(name.indexOf(b) !== -1){name.splice(name.indexOf(b),1)a.className = name.join(" ");console.log(&#39;obj.className=&#39;+a.className)}else{console.log(&#39;不变&#39;)}}
   addClass(obj, &#39;new&#39;) // obj.className=&#39;open menu new&#39;    addClass(obj, &#39;open&#39;)  // 因为open已经存在,此操作无任何办法    addClass(obj, &#39;me&#39;) // obj.className=&#39;open menu new me&#39;    console.log(obj.className)  // "open menu new me"    removeClass(obj, &#39;open&#39;) // obj.className=&#39;menu new me&#39;    removeClass(obj, &#39;blabla&#39;)  // 不变
Copy after login

Write a camelize function to convert a string in the form of my-short-string into a string in the form of myShortString, such as:


camelize("background-color") == &#39;backgroundColor&#39;
camelize("list-style-image") == &#39;listStyleImage&#39;
Copy after login

Code:


function camelize(string){
return string.replace(/-/g,'')
}
console.log(camelize("background-color"))
camelize("background-color") == &#39;backgroundColor&#39;
camelize("list-style-image") == &#39;listStyleImage&#39;
Copy after login

What does the following code output? Why?


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

Because arr.push( function() { alert(console.log('hello hunger valley')) } );change function() { alert(console.log('hello hunger valley')push to the last bit of arr[], arr[arr.length-1]() takes the last bit of the array, and then executes the function immediately, because function() { alert(console.log('hello hunger valley') console.log is only allowed to be opened in the console, so the result is undefined.


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


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

Code:


arr = ["a","d", 1,3,4,5, "b", 2];
//对原数组进行操作,不需要返回值
function filterNumericInPlace(data){
for(i=0;i<data.length;i++){
if(typeof data[i] === &#39;string&#39;){
data.splice(i,1);
i--;//splice指针减少1,否则获取不了数组中全部元素。
}
}
}
filterNumericInPlace(arr);
console.log(arr)  // [1,3,4,5,2]
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 ]
ageSort(people) // [ bob, mary, john ]
Copy after login

Code:

Method 1:

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

Method 2:


function ageSort(a){
for(i=0;i0){
var b = a[i];
a[i] = a[j];
a[j] = b;
}
}
}
return a
}
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 ]
ageSort(people) // [ bob, mary, john ]
console.log(ageSort(people))
Copy after login

Write a filter(arr, func) function to filter the array, accepting 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. When the function returns true, the element is retained, otherwise the element is deleted). Implement the following functions:

function isNumeric (el){return typeof el === &#39;number&#39;;}arr = ["a",3,4,true, -1, 2, "b"]
 arr = filter(arr, isNumeric) ; // arr = [3,4,-1, 2],  过滤出数字  arr = filter(arr, function(val) { return val > 0 });  // arr = [2] 过滤出大于0的整数
Copy after login

Code:

##. #

function filter(data,callback){return data.filter(callback)}
   function isNumeric (el){        return typeof el === &#39;number&#39;;     }    arr = ["a",3,4,true, -1, 2, "b"]    arr = filter(arr, isNumeric) ; // arr = [3,4,-1, 2],  过滤出数字    console.log(arr)    arr = filter(arr, function(val) { return val > 0 });  // arr = [2] 过滤出大于0的整数    console.log(arr)
Copy after login

String

Write a ucFirst function that returns the character whose first letter is uppercase

ucFirst("hunger") == "Hunger"
Copy after login

Code:

function ucFirst(string){
return string[0].toUpperCase()+string.slice(1);
}
console.log(ucFirst("hunger"))
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:

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

Code:

function truncate(str,maxlength){
if(str.length>maxlength){
var sub = str.substring(maxlength)
str =  str.replace(sub,&#39;...&#39;);
} return str;
}
console.log(truncate("hello, this is hunger valley,", 10));
truncate("hello, this is hunger valley,", 10) == "hello, thi...";
truncate("hello world", 20) == "hello world"
Copy after login

Mathematical function

Write a function limit2, keep the number to two decimal places, and round, such as:

var num1 = 3.456
limit2( num1 );  //3.46
limit2( 2.42 );    //2.42
Copy after login

Code:

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

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

Code:


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

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

Code:


function fun(min,max){
return Math.Round(min+Math.random()*(max-min))
}
console.log(fun(5,10))
Copy after login

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

Code:


function fun(min,max,leng){
var arr = []
for(i=0;i<leng;i++){
var value = max-Math.random()*(max-min)
arr.push(value)
}
return arr
}
console.log(fun(5,10,6))
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Related reading:

JS closures and timers


JS Dom and event summary

The above is the detailed content of JavaScript Array-String-Math Function. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to determine whether a Golang string ends with a specified character How to determine whether a Golang string ends with a specified character Mar 12, 2024 pm 04:48 PM

Title: How to determine whether a string ends with a specific character in Golang. In the Go language, sometimes we need to determine whether a string ends with a specific character. This is very common when processing strings. This article will introduce how to use the Go language to implement this function, and provide code examples for your reference. First, let's take a look at how to determine whether a string ends with a specified character in Golang. The characters in a string in Golang can be obtained through indexing, and the length of the string can be

How to intercept a string in Go language How to intercept a string in Go language Mar 13, 2024 am 08:33 AM

Go language is a powerful and flexible programming language that provides rich string processing functions, including string interception. In the Go language, we can use slices to intercept strings. Next, we will introduce in detail how to intercept strings in Go language, with specific code examples. 1. Use slicing to intercept a string. In the Go language, you can use slicing expressions to intercept a part of a string. The syntax of slice expression is as follows: slice:=str[start:end]where, s

How to repeat a string in python_python repeating string tutorial How to repeat a string in python_python repeating string tutorial Apr 02, 2024 pm 03:58 PM

1. First open pycharm and enter the pycharm homepage. 2. Then create a new python script, right-click - click new - click pythonfile. 3. Enter a string, code: s="-". 4. Then you need to repeat the symbols in the string 20 times, code: s1=s*20. 5. Enter the print output code, code: print(s1). 6. Finally run the script and you will see our return value at the bottom: - repeated 20 times.

Detailed explanation of the method of converting int type to string in PHP Detailed explanation of the method of converting int type to string in PHP Mar 26, 2024 am 11:45 AM

Detailed explanation of the method of converting int type to string in PHP In PHP development, we often encounter the need to convert int type to string type. This conversion can be achieved in a variety of ways. This article will introduce several common methods in detail, with specific code examples to help readers better understand. 1. Use PHP’s built-in function strval(). PHP provides a built-in function strval() that can convert variables of different types into string types. When we need to convert int type to string type,

How to check if a string starts with a specific character in Golang? How to check if a string starts with a specific character in Golang? Mar 12, 2024 pm 09:42 PM

How to check if a string starts with a specific character in Golang? When programming in Golang, you often encounter situations where you need to check whether a string begins with a specific character. To meet this requirement, we can use the functions provided by the strings package in Golang to achieve this. Next, we will introduce in detail how to use Golang to check whether a string starts with a specific character, with specific code examples. In Golang, we can use HasPrefix from the strings package

How to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP How to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP Mar 04, 2024 am 09:36 AM

Methods to solve Chinese garbled characters when converting hexadecimal strings in PHP. In PHP programming, sometimes we encounter situations where we need to convert strings represented by hexadecimal into normal Chinese characters. However, in the process of this conversion, sometimes you will encounter the problem of Chinese garbled characters. This article will provide you with a method to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP, and give specific code examples. Use the hex2bin() function for hexadecimal conversion. PHP’s built-in hex2bin() function can convert 1

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles