search
HomeWeb Front-endJS TutorialDeep dive into the basics of JavaScript

Deep dive into the basics of JavaScript

Mar 13, 2018 pm 01:19 PM
javascriptjsapplication

This time I will bring you in-depth JavaScript basic applications, What are the precautions for using JavaScript basic applications, the following are practical cases, let’s take a look take a look.

Function return value

Return value 1

<script>function show(){    return &#39;advb&#39;;
}var a=show();
alert(a); // 结果: advb</script>

Return value 2

<script>function show(a, b){    return a+b;
}
alert(show(3, 5));</script>

Return value 3

<script>function show(a, b){    //return; //没有return}
alert(show(3, 5));  //结果 : undefined</script>
<script>function show(a, b){    return; //没有return任何东西}
alert(show(3, 5));  //结果 : undefined</script>

General summation

<script>function sum(a, b){    return a+b;
}
alert(sum(12, 6));</script>

Sum of multiple parameters (arguments is a variable array)

<script>
    function sum()    {        //arguments 是一个可变数组 
        var result=0;        for(var i=0;i<arguments.length;i++)
        {
            result+=arguments[i];
        }        return result;
    }
    alert(sum(12, 6, 8, 6, 8, 6, 8)); //结果 : 54</script>```

- CSS function gets properties when two parameters are passed in, and changes when three parameters are passed in Style

<html>
<head>
<meta charset="utf-8">
<title>CSS函数</title>
<script>
function css(obj, name, value)
{
if(arguments.length==2) //获取
{
return obj.style[name];
}
else
{
obj.style[name]=value; //修改
}
}
window.onload=function ()
{
var oDiv=document.getElementById(&#39;div1&#39;);
//alert(css(oDiv, &#39;width&#39;)); //获取到宽度 200px
css(oDiv, &#39;background&#39;, &#39;green&#39;); //修改背景颜色为绿色
};
</script>
</head>
<body>
<div id="div1" style="width:200px; height:200px; background:red;">
</div>
</body>
</html>
function getStyle(obj, name)
{if(obj.currentStyle) //由于currentStyle只兼容IE,所以在IE浏览器中他是true,其他浏览器中为false
{
return obj.currentStyle[name]; //IE
}
else
{    //计算样式 其中getComputedStyle(oDiv, xxx) 第二个参数可以随便填,一般习惯写false
return getComputedStyle(obj, false)[name];  //Chrome、FF
}
}

Sample code:
Use the above function to obtain the non-interline style `backgroundColor`

window.onload=function (){var oDiv=document.getElementById(&#39;div1&#39;);
alert(getStyle(oDiv, &#39;backgroundColor&#39;));
};


NoteThis function only Applicable to single style, composite style is not applicable!!!
Single style: width, height, position, etc.
Composite style: background, border, etc.
>
3. Array - Array basics
- Array usage

Definition


var arr=[12, 5, 8, 9]; //一般用这种创建方式,简单
var arr=new Array(12, 5, 8, 9); //也可以这样创建

There is no difference, [] has slightly higher performance because the code is shorter



- Array The attribute

length



can both be obtained and set: ①. You can get the number of arrays, ②. You can also use array.length = 1; to set the number of arrays;

Example: Quickly clear the array //Use array.length = 0; to clear the array;

Principles for using arrays: Only one type of variables should be stored in the array

- Array methods

Add

push(element), add an element from the tail

unshift(element), add an element from the head

Delete


pop(), delete an element from the tail

shift(), delete an element from the head

- insert and delete `splice` (`phonetic symbol:[splaɪs]`): universal of arrays Operation

Delete

splice(start, length) //First parameter: Specify the position; Second parameter: Specify the length

Insert

splice(start, 0, element...)

Delete first, then insert


splice(start, length, element...)

Delete first, then insert

Replacement

Delete first, then insert, which can be used as replacement

-Array connection (merge two arrays):concatconcat(array 2)

Connect two Array


<script>
var a = [1,2,3];
var b = [4,5,6];
alert(a.concat(b)); 结果:[1,2,3,4,5,6];
alert(b.concat(a)); 结果:[4,5,6,1,2,3];
</script>

- join(separator)

Use the delimiter to combine array elements to generate a string (when learning ajax, use it to connect the URL)


<script>
var arr = [1,2,3,4];
alert(arr.join(&#39;-&#39;)) //1-2-3-4
alert(arr.join(&#39;- -p&#39;)) //1- -p2- -p3- -p4
</script>

- String split (`[splɪt]`Separate; decompose) The split() method is used to split a string into a string array. stringObject.split(separator,howmany)


separator Required. A string or regular expression to split the stringObject from where specified by this parameter.

howmany Optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings will be returned than the array specified by this parameter. If this parameter is not set, the entire string will be split regardless of its length.

Using


If you want to split a word into letters, or a string into characters, use the following code:


"hello".split("")   //可返回 ["h", "e", "l", "l", "o"]

If you only need to return a part of characters, please use howmany parameters:


"hello".split("", 3)    //可返回 ["h", "e", "l"]

- Sort sort`sort([Comparison function])`, sort an array
Sort a string array
Sort a numeric array

① Sort a string array


<script>
var arr=[&#39;float&#39;, &#39;width&#39;, &#39;alpha&#39;, &#39;zoom&#39;, &#39;left&#39;];
arr.sort();
alert(arr); //结果 [&#39;alpha&#39;,&#39;float&#39;,&#39;left&#39;,&#39;width&#39;,&#39;zoom&#39;]
</script>

② Sort a numeric array - 2.1 Basic Edition


<script>
var arr=[12, 8, 99, 19, 112];
arr.sort();
alert(arr); //结果: [112,12,19,8,99] //其实他把数字当成字符串来排序了
</script>

- 2.1 Advanced Edition


<script>
var arr=[12, 8, 99, 19, 112];
arr.sort(function (n1, n2){
if(n1<n2)
{
return -1;//只要是个负数就可以 -2,-7等都可以
}
else if(n1>n2)
{
return 1; //只要是个正数就够了
}
else
{
return 0;
}
});
alert(arr); //结果:[8,12,19,99,112]
</script>

- 2.2 final version (evolved from 2.1)

<script>var arr=[12, 8, 99, 19, 112];
arr.sort(function (n1, n2){    return n1-n2; //若果n1>n2,为正;如果n1<n2,为负;如果相等,则为0;});alert(arr);//结果:[8,12,19,99,112]
</script>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website

Other

related articles!

Recommended reading:
Background-related attributes in HTML and CSS


8 basic knowledge that must be paid attention to in JS

######

The above is the detailed content of Deep dive into the basics of JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools