JavaScript --- network programming (2) - functions and arrays

Familiar with memory 2021-01-21 12:55:28
javascript network programming functions arrays


Last section , It's the end of the cycle ~ Now learn Javascript Functions and arrays of . JavaScript grammar Every language has its own grammatical rules ,JS Syntax and Java It's like , So it's easier to learn .JS It's the same with variables , sentence , function , Array and other common language elements .

1. General functions Format :

function Function name ( Formal parameters ...)
{
Execute statement ;
return Return value ;
}

A function is an encapsulation of multiple executing statements , Only when called will it be run . Be careful : Call functions with parameters , But I didn't give it a value , Functions can also run , Or call a function without parameters , Pass the value to it , This function works the same way . Keep it simple : Just write the function name followed by a pair of parentheses , The function will run . What about the parameters to be passed ? Actually , There is a parameter array object in the function (arguments), This object encapsulates the parameters passed in an array . example :

function demo()// Defined function .
{
alert(arguments.length);
}

demo(“hello”,123,true);// Call function . So the result of the pop-up dialog is 3, If you want to get all the parameter values , Can pass for Loop through the array .

for(var x=0; x<arguments.length; x++)
{
alert(arguments[x]);
}

To enhance readability , It's better to follow the rules , Transfer the actual parameters according to the defined formal parameters . Other ways of writing functions when they are called : var show = demo();//show Variable reception demo The return value of the function . var show = demo;// This kind of writing is OK , Meaning for show and demo Represents the same function . // So this function can also be passed through show() How to run .

Code demonstration 1:

<html>
<head>
<title>javascript Function usage demonstration </title>
</head>
<body>
<!--
※java The format of function definition in :
int sum(int a,int b){
....
return s
}
※js The format of function definition in :
function sum(a,b){
....
return s
}
▲▲js The function in can be understood as a function Object of type
-->
<script type="text/javascript">
//※ The browser to js Code is executed while parsing
// Be careful , Function call It should be resolved in the browser The definition of this function after
// call
hello();//ie11 Invalid in --- Because when the browser parses the statement , This function has not been defined yet
</script>
<script type="text/javascript">
// Definition --- Nonparametric functions
function hello(){
document.write("hello function!");
}
hello();// call
// Definition --- There are parametric functions
function add(a,b){
var s = a+b;
return s;
}
document.write("<br/>")
document.write("s="+add(10,23));
</script>
</body>
</html>

360 browser 8.1 demonstration 1 result :

Code demonstration 2:

<html>
<head>
<title>javascript Function usage demonstration 2--- A little bit of detail </title>
</head>
<body>
<script type="text/javascript">
function show(x, y) {
document.write(x + "," + y);
document.write("<br/>");
}
show(23, 22);//23,22
show(23); //23,undefined
show(); //undefined,undefined
show(23, 22, 11);//23,22 The latter parameter function receives but does not work
// The arguments to the function are all js Use a... Inside arguments Array to receive and store --- The object is js What internal implication does for us , We can access this array object
function show2(x, y) {
arguments[0] = 1000;// You can put the formal parameters x Change the value of
document.write(x + "," + y + "<br/>");
for ( var i = 0; i < arguments.length; i++) {
document.write(arguments[i] + ",");
}
}
show2(11, 22, 33, 44);
document.write("<br/>");
//※ Sum up , Technical details of functions :
//1, js The function in is not overloaded , Identified only by function name --- In fact, the function name is a function The name of the reference to the object
//2, js There is an internally maintained arguments Array to receive and save formal parameters
</script>
<script type="text/javascript">
function getValue() {
document.write("aa");
document.write("<br/>");
return 100;
}
var v = getValue();
document.write("v=" + v);
document.write("<br/>");
var v2 = getValue; // amount to getValue Pass the reference value to v2, therefore v2 Also a “function object ”----getValue and v2 All reference variables
document.write("v2=" + v2);// It's actually output v2 Object's toString()
document.write("<br/>");
document.write("v2=" + v2()); // call v2 This function object --- Call function
document.write("<br/>");
</script>
</body>
</html>

360 browser 8.1 demonstration 2 result :

 Dynamic functions adopt Js Built in objects for Function Realization . example :

 var demo = new Function(“x,y”;”alert(x+y);”);
demo(4,6);
Like :
function demo(x,y)
{
alert(x+y);
}
demo(4,6);

The difference is , Dynamic functions , Parameters and function bodies can be passed through parameters , You can dynamically specify .

Anonymous functions Format : function(){…} example : var demo = function(){…} demo(); It is often used to define the behavior of event properties . example :

function test()
{
alert(“load ok”);
}
window.onload = test;

It can be written as an anonymous function :

window.onload = function()
{
alert(“load ok”);
}

Anonymous functions are a shorthand format .

Code demonstration :

<html>
<head>
<title>javascript Function usage demonstration 3--- Dynamic functions , Anonymous functions </title>
</head>
<body>
<!--
※1※ Dynamic functions : It uses js An object built into ---- Function
Be careful , Lowercase function It's used to declare , And capital Function It's for new Object's
// Write the following functions as dynamic functions
function add(a,b){
var s = a+b;
return s;
}
-->
<script type="text/javascript">
// Let's use the formal parameter of the function as the second 1 Parameters passed in , The code in the body of the function is written in 2 Parameters passed in ---- The function body can be passed in dynamically through the caller , So it's very flexible , The idea is similar to Java Class reflection in it .
var add = new Function("a,b","var s = a+b; return s; ");
document.write( add(12,13) );
</script>
<!--
※2※ Anonymous functions : Functions without function names . We will often use this method in event processing in the future , similar Java Anonymous inner classes in are often used in event listeners as well
-->
<script type="text/javascript">
var fun= function(a,b){
return a+b;
};
document.write( fun(2,3) );
</script>
<!-- Use anonymous function to add event binding to button -->
<button id="btn1"> A button </button>
<script type="text/javascript">
btn1.onclick=function(){
alert('aa');
};
</script>
</body>
</html>

360 browser 8.1 Results, :

Popup :

5. Array Easy to operate multi-element container , You can number the elements . characteristic : You can store any element , The length is variable . Format :

var arr = new Array();
arr[0] = “hello”;
arr[1] = 123;
var arr = [‘hello’,123,true,”abc”];

You can perform basic operations on arrays by traversing .

for(var x=0; x<arr.length; x++)
{
alert(arr[x]);
}

Code demonstration :

<html>
<head>
<title>javascript Array usage demonstration </title>
</head>
<body>
<script type="text/javascript">
// How to define an array 1: When defining, the initial value is assigned directly
var arr =[12,34,2,-3,90,12];
document.write( typeof(arr) );
//object
document.write("<br/>");
document.write("len:" + arr.length);
document.write("<br/>");
// Traversal array
for(var x=0;x<arr.length;x++){
document.write("arr["+x+"]="+ arr[x]+"&nbsp;");
}
document.write("<br/>");
arr[0]=-10;
arr[7]=66;// Arrays can grow automatically , And arr[6] If there is no assignment, then undefined
document.write("len:"+arr.length+" The array length is automatically lengthened ");
document.write("<br/>");
for(var x=0;x<arr.length;x++){
document.write("arr["+x+"]="+ arr[x]+"&nbsp;");
}
document.write("<br/>");
document.write("<hr/>");
var arr2=[];
document.write("arr2.length="+arr2.length);//0
document.write("<br/>");
arr2[1]=10;
for(var x=0;x<arr2.length;x++){
document.write("arr2["+x+"]="+ arr2[x]+"&nbsp;");
}
document.write("<br/>");
//※※ Wrong way to declare -- Array
//int[] arr3 ={1,2,3};
//var[] arr3 = [1,2,3];// In the wrong ,[] Represents the array type , and js in , There is only one data type var Statement , non-existent “var[]” This type of
document.write(" The elements of the same array can be of different types !!!<br/>");
var arr4=[1,2,3,100];
arr4[0]="abc";
arr4[1]=true;
for(var x=0;x<arr4.length;x++){
document.write("arr4["+x+"]="+ arr4[x]+"&nbsp;");
}
document.write("<br/>");
//※※ Sum up ,js Two characteristics of arrays :
//1, The length is variable
//2, The type of element is arbitrary
</script>
<hr/>
<script type="text/javascript">
// How to define an array 2: Use js Medium Array Object to define
var arr10 = new Array(); //※ Empty ginseng
for(var x=0;x<arr10.length;x++){
document.write("arr10["+x+"]="+ arr10[x]+"&nbsp;");
}// Nothing there? , Because the length is 0
document.write("arr10.length="+arr10.length);//0
document.write("<br/>");
var arr11 = new Array(8); //※ One parameter , Represents the length of the array
arr11[2]=12;
arr11[3]="abc";
for(var x=0;x<arr11.length;x++){
if(x==2||x==3){
document.write("<font color=red >arr11["+x+"]="+ arr11[x]+"&nbsp;</font>");
}else{
document.write("arr11["+x+"]="+ arr11[x]+"&nbsp;");
}
}
document.write("<br/>");
var arr12 = new Array(10,11,12); //※ Multiple parameters , Represents the value of an array element
arr12[5]="aaa";
for(var x=0;x<arr12.length;x++){
document.write("arr12["+x+"]="+ arr12[x]+"&nbsp;");
}
document.write("<br/>");
</script>
</body>
</html>

360 browser 8.1 Results, :

Next, combine functions with arrays , Write a sort and binary search .

<html>
<head>
<title>javascript Array and function exercises </title>
</head>
<body>
<script type="text/javascript">
// Write a function to get the maximum value of the elements in the array
// If there are multiple , Return to the first
function getMax(arr){
var max=0;// The subscript of the maximum value
for(var x=1;x<arr.length;x++){
if(arr[x]>arr[max]){
max = x;
}
}
return arr[max];
}
// call
var arr=[23,-3,45,0,-100,47,22];
var v = getMax(arr);
document.write(" The subscript of the maximum value of an array :"+v);
document.write("<br/>");
document.write(" Array maximum :"+v);
document.write("<br/>");
// Array selection sort
function sortArray(arr){
for(var x=0;x<arr.length-1;x++){
var min=x;
for( var y=x+1;y<arr.length;y++){
if(arr[min]>arr[y]){
min=y;
}
}
if(min!=x){
swap(arr,x,min);
}
}
}
function swap(arr,x,y){
var temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
document.write("<hr/>");
document.write(" Before ordering :"+arr+"<br/>");
sortArray(arr);
document.write(" After ordering :"+arr+"<br/>");
// Our output function --- Output the content to the page and wrap it
function println(str){
document.write(str+"<br/>");
}
println(arr);
sortArray(arr);
println(arr);
// Find elements in an array
function searchElement(arr,key){
for(var x=0;x<arr.length;x++){
if(arr[x]==key){
return x;
}
}
return -1;
}
println( searchElement(arr,0) );
println( searchElement(arr,123) );
</script>
<script type="text/javascript">
// Two points search
function binarySearch(arr,key){
var max,min,mid;
min=0;
max=arr.length-1;
while(min<=max){
mid = (max+min)>>1;
if(key>arr[mid]){// On the right
min = mid+1;
}else if(key<arr[mid]){// It's on the left
max = mid-1;
}else{
return mid;
}
}
return -1;
}
println(" Binary search results :");
println( binarySearch(arr,0) );
println( binarySearch(arr,123) );
// An array of reverse
function reverseArray(arr){
for(var start=0,end=arr.length-1; start<end; start++,end--){
swap(arr,start,end);
}
}
reverseArray(arr);
println(" After reversing :"+arr);
</script>
</body>
</html>

360 browser 8.1 Results, :

JS Global variable and local variable solutions in :

Code demonstration :

<html>
<head>
<title>javascript Global variables and local variables in </title>
</head>
<body>
<!--
Global variables : js in , The variables defined directly in the script are all global variables .
local variable : Variables defined in a function are local .
-->
<script type="text/javascript">
function println(str){
document.write(str+"<br/>");
}
var a=100;
println(" Traverse the output 0-9:");
for(var x=0;x<10;x++){
println("x="+x);
}
</script>
<script type="text/javascript">
println("aaaa="+a);
println("xxxx="+x);
function aa(){
var y=123;
document.write("y="+y);
return;
}
aa();
document.write("<br/>");
println("yyyy="+y);// Cannot access variables defined inside a function , Because it's local
</script>
<!-- A little bit of detail -->
<script type="text/javascript">
var n=3;// Global variables n
function abc(n){// local variable n--- Formal parameters are local variables declared inside a method , Values are determined by arguments[0] In the use of n It was given to it temporarily
n=6;
}
abc(n);// hold x Pass it on to the method abc, And try to change the value in it -- Attempted !---- In essence, arguments n It's passing the value to... In the function arguments Array
println("n="+n);
</script>
</body>
</html>

360 browser 8.1 Results, :

Next time, learn JS The object. . After all JS It's object-based language .

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Familiar with memory]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121125355078Y.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云