Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Getting started with JavaScript for cloud development


May 22, 2021 Mini Program Cloud Development Study Guide


Table of contents


JavaScript is one of the most popular programming languages in the world, and it is also the most important basic language for small program development. To make a small, complex program, in addition to mastering the basic syntax of JavaScript, you also need to know how to use JavaScript to manipulate small programs (via the API interface).

Console Console

Open the WeChat developer tool and you can see the labels Console, Sources, Network, Appdata, Wxml, etc. in the debugger, which are the functional modules of the debugger. In addition to displaying error messages for small programs, console Console can also be used to enter and debug code.

Mathematical operations

JavaScript's arithmetic operators are not much different from our common mathematical operators, plus, minus, multiplication, division/, exponential, and we can enter line-by-line after console Console's and follow Enter to execute the following code:

  1. 136+384; //加法
  2. (110/0.5+537-100)*2; //加减乘除
  3. 2**5; //指数运算符

Comments for JavaScript, which can be entered without input and without impact; Separated.

Console .log print logs

Entering four operations in the console can get the result directly because the console.log() function is called, we can print the above four operations in the console using console.log (321 x 3), in addition to the four operations, console .log() can also print the string String, for example:

  1. console.log("童鞋,欢迎开始JavaScript的学习~\nJavaScript是一门非常流行的编程语言,只要是有浏览器的地方就少不了JavaScript;\n网页、小程序、甚至App、桌面应用等都少不了JavaScript;\nJavaScript玩得溜的人我们可以称其为前端开发工程师;\n前端开发工程师是需求量极大的岗位\n");
  2. console.log('%c欢迎关注小程序的云开发:https://www.zhihu.com/org/teng-xun-yun-kai-fa-tcb (用云开发可以更快速学好前端开发)','color: red' );

In practice, there are always characters with special meanings that cannot be entered \n such as \t tab key, \r backslash, which we call escape characters. \\ B oth single and double quotes in JavaScript represent strings. I f there are double quotes in the string, single quotes are recommended for the outern layer, and double quotes for the outern layer if single quotes are present in the string. How to add color to printed fonts in the console, etc., you can study for yourself.

Console .log print array Array

We can print the array using .log() in the console, and after printing it out, the result will be preceded by a number showing the length of the array, and it can be expanded.

  1. console.log(["肖申克的救赎","霸王别姬","这个杀手不太冷","阿甘正传","美丽人生"])

In the expanded results, we can see the index of the array, as well as the corresponding values of the index index index (e.g.: 1: "Overlord Becky"), the length of the array, and the method of the array (as can be seen in proto, such as concat, push, shift, slice, toString, etc.).

We can also print a single data in an array by indexing values, that is, by specifying the array name and index value, to access a particular element:

  1. console.log(["肖申克的救赎","霸王别姬","这个杀手不太冷","阿甘正传","美丽人生"])

Console .log the print object Object

In the console, an object object .log object Object is printed using the console function, and the result of the object can still be expanded through the triangle on the left to see the properties of the object and the values corresponding to the properties.

  1. console.log({name: "霸王别姬",img: "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1910813120.webp",desc: "风华绝代。"})

We can access the property by point notation to get the value corresponding to the property:

  1. console.log({name: "霸王别姬",img: "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1910813120.webp",desc: "风华绝代。"}.desc)

When we print an item in an array and get a value for an object's property by point notation, do we feel that the print is too long? At this point we can assign arrays and objects to a variable, similar to the math of y-ax-b, which greatly simplifies the code.

Variables and assignments

JavaScript can declare a variable using a let statement, using an equal sign to assign a value to a variable, an equal sign to the left for a variable name, and a value to the right for that variable, which can be of any data type. JavaScript's common data types are Number, String, Boolean, Object, Function, and so on.

Assign the data to a variable

For example, in the console, we can assign the above array and object to a variable, and then print the variable, first print the array:

  1. let movielist=["肖申克的救赎","霸王别姬","这个杀手不太冷","阿甘正传","美丽人生"]
  2. console.log(movielist)
  3. console.log(movielist[2])

Let's look at the printed objects:

  1. let movie={name: "霸王别姬",img: "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1910813120.webp",desc: "风华绝代。"}
  2. console.log(movie)
  3. console.log(movie.name)

By assigning complex data information (arrays, objects) to a variable, the code is greatly simplified and it is possible to understand that variables are "containers" for storing information.

Conflicts and overrides of variables

For example, in the console Console, we use the let to declare a variable, usrname, and then print out the username:

  1. let username="小明"
  2. console.log(username)

But if you use the let to declare the username again and assign the username a variable name conflict, such as entering the following code in the console and pressing Enter, what will be the error?

  1. let username="小丸子"

That is, after a variable name has been declared, you cannot declare the variable name again. But we can re-assign the variable, for example:

  1. username="小军"
  2. console.log(username)

We found that after we re-assign the variable, the value of the variable is overwritten. So the let variable name is a value, which is equivalent to a two-step operation, the first step is to declare the variable name, and the second step is to assign a value to the variable, which can be understood by the following code executed by the console.

  1. let school //声明变量
  2. school="清华" //将字符串String"清华"赋值给变量
  3. console.log(school) //打印变量
  4. school=["清华","北大","上交","复旦","浙大","南大","中科大"] //给变量赋值新的数据类型新的数据
  5. console.log(school) //打印变量

By using the console to print specific information in action, we will have a better understanding of declaring variables, assigning values, overlays (modifying the values of variables).

This undefined is the return value of the function .log console.log) and each function has a return value, which is returned if the function does not provide a return value.

  1. 小任务:那我们是否可以给一个没有声明过的变量名直接赋值呢?你知道应该如何在控制台打印测试结果吗?你的实验结果是?

The array of operations

As we said earlier, arrays are an ordered list. Here's an array of top5s from the bean petal movie:

  1. ["肖申克的救赎","霸王别姬","这个杀手不太冷","阿甘正传","美丽人生"]

But sometimes we need to manipulate the array, such as want to add 5 data, become top10, such as too much data, just want top3 and so on, this time we need to operate on the array. T o manipulate an array, there is a way to do it. W e've assigned the array to movielist earlier, so we can use the variable directly. You can also assign it in the console.

  1. movielist=["肖申克的救赎","霸王别姬","这个杀手不太冷","阿甘正传","美丽人生"]

Separator line method

The join method stitches array elements into strings, split by separators, which by default are commas.

  1. console.log(movielist.join("、"))

Add an array push method

The push() method adds one or more elements to the end of the array and returns the length of the new array.

  1. console.log(movielist.push("千与千寻","泰坦尼克号","辛德勒的名单","盗梦空间","忠犬八公的故事"))

The length of the new array is returned here, so let's print the new array to see which values are included, and the push method adds five new values (not overwriting, re-assignment) after the original array (not the previous one).

  1. console.log(movielist)

Remove the last pop method

Pop() removes the last item from the end of the array and returns the value of the removed item:

  1. console.log(movielist.pop())

Returning the last item of the array, let's print movielist again to see what happens:

  1. console.log(movielist)

The above through some practical cases let us know how to use the console printing this real-world way to understand some array specific operation methods, array operation methods are many, you can go to the technical documentation.

Technical documentation: Array Array

If the development of small programs can not be separated from the official technical documentation of small programs, then MDN is every front-end development engineer must often go through the technical documents. H itting the MDN array Array, in the menu on the left side of the page, we can see that Array has dozens of methods, all of which we saw in proto after we printed the array before. With regard to the prototype of arrays, those who have the ability to learn can read MDN Array.Prototype

  1. 小任务:通过实战的方式了解一下数组的concat()、reverse()、shift()、slice()、sort()、splice()、unshift()方法

The action object

We can access the properties of an object by point notation, and by assigning a value to that property, we can add and modify the value of the object's properties. Before we declared an object movie:

  1. movie={name: "霸王别姬",img: "https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1910813120.webp",desc: "风华绝代。"}

Add properties to the object

For example, we add the properties of the English name to the overlord Becky and enter the following code directly in the console:

  1. movie.englishname="Farewell My Concubine"

Then print the movie in the console to see if the movie has the properties of englishname

  1. console.log(movie)

Delete a property of the object

For example, if we want to remove the img property of movie, we can delete it by delete method

  1. delete movie.img

Then print the movie in the console to see if the movie's img property has been deleted.

  1. console.log(movie)

Update a property of an object

For example, we want to update the desc property of movie, which can be updated by re-assigning

  1. movie.desc="人生如戏。"

Then print the movie in the console to see if the desc property of the movie has changed.

  1. console.log(movie)

Constant

Earlier we knew that the value of a variable could be changed by re-assigning it, but some data we want to be fixed (write dead, not change very often), at which point you can use the const declaration to create a read-only reference to the value. The const statement is quite like the let statement.

For example, when developing small programs, we will determine the color system of small programs, colors, etc. , the use of const declaration, later directly call this constant, so that you do not have to remember so many complex parameters, later want to change the whole network style, directly change the content of const can be. Like what:

  1. const defaultStyle = {
  2. color: '#7A7E83',
  3. selectedColor: '#3cc51f',
  4. backgroundColor: '#ffffff',
  5. }

The operation of the string

We already know that strings are one of JavaScript's data types, so how can we manipulate strings? L et's study in conjunction with the MDN technical documentation. MDN documents are the technical documents that the front end relies on most, and we need to learn how to use them like a dictionary.

Technical documentation: String of the JavaScript standard library for technical documentation

First we .js the following code in the main console, then execute to see the effect in the Console console:

  1. let lesson="云开发技术训练营";
  2. let enname="CloudBase Camp"
  3. console.log(lesson.length); //返回字符串的长度
  4. console.log(lesson[4]); //返回在指定位置的字符
  5. console.log(lesson.charAt(4)); //返回在指定位置的字符
  6. console.log(lesson.substring(3,6)); //从索引3开始到6(不包括6)
  7. console.log(lesson.substring(4)); //从索引4开始到结束
  8. console.log(enname.toLowerCase()); //把一个字符串全部变为小写:
  9. console.log(enname.toUpperCase()); //把一个字符串全部变为大写:
  10. console.log(enname.indexOf('oud')); //搜索指定字符串出现的位置:
  11. console.log(enname.concat(lesson)); //连接两个字符串
  12. console.log(lesson.slice(4)); //提取字符串的某个部分,并以新的字符串返回被提取的部分

Then open the technical documentation, in the properties and methods of the menu on the left side of the technical document, find out which properties and methods are used to manipulate the string, and read through the technical documentation to deepen the understanding of each operation of the string, but also know how to consult the technical documentation.

Why do strings have so many properties and methods? M ore is right, it is precisely because of more, so we can not use the traditional rote mest to learn technology. H ow come there are so many new words in technical documentation that I haven't seen before and I don't understand them at all? Y ou don't need to understand everything, just as we don't need to understand all the words and grammar in the dictionary. Even the GRE master can't recognize all the words, and usually level 6 words are enough, and the technology is the same.

Math object

Math is a built-in object that has properties and methods of mathematical constants and functions, but it is not a function object. You can fight in the console before you understand the meaning of this sentence.

Technical documentation: Math object documentation

Enter the following code in the console console of the developer tool to figure out the meaning of each function based on the results obtained.

  1. let x=3,y=4,z=5.001,a=-3,b=-4,c=-5;
  2. console.log(Math.abs(b)); //返回b的绝对值
  3. console.log(Math.round(z));//返回z四舍五入后的整数
  4. console.log(Math.pow(x,y)) //返回x的y次幂
  5. console.log(Math.max(x,y,z,a,b,c)); //返回x,y,z,a,b,c的最大值
  6. console.log(Math.min(x,y,z,a,b,c));//返回x,y,z,a,b,c的最小值
  7. console.log(Math.sign(a)); //返回a是正数还是负数
  8. console.log(Math.hypot(x,y)); //返回所有x,y的平方和的平方根
  9. console.log(Math.PI); //返回一个圆的周长与直径的比例,约3.1415

Let's open the technical documentation and look at the properties of the Math object in the left menu, and what are the methods of the Math object? Get a rough idea of what a subordinate and method really means.

Note that in other development languages, we want to get an absolute value of a number that can call the abs(x) function directly, whereas JavaScript is Math.abs(x), because the previously mentioned Math is not a function (function object) but an object.

Date object

Date objects are used to process dates and times. Time has the concept of year, month, day, week, hour, minute, second, millisecond, and time zone, so Date object properties and methods are also more.

Technical documentation: Date object documentation

  1. let now = new Date(); //返回当日的日期和时间。
  2. console.log(now);
  3. console.log(now.getFullYear()); //从 Date 对象以四位数字返回年份。
  4. console.log(now.getMonth()); //从 Date 对象返回月份 (0 ~ 11)。
  5. console.log(now.getDate()); //从 Date 对象返回一个月中的某一天 (1 ~ 31)。
  6. console.log(now.getDay()); //从 Date 对象返回一周中的某一天 (0 ~ 6)。
  7. console.log(now.getHours()); //返回 Date 对象的小时 (0 ~ 23)。
  8. console.log(now.getMinutes()); //返回 Date 对象的分钟 (0 ~ 59)。
  9. console.log(now.getSeconds()); //返回 Date 对象的秒数 (0 ~ 59)。
  10. console.log(now.getMilliseconds()); //返回 Date 对象的毫秒(0 ~ 999)。
  11. console.log(now.getTime()); //返回 1970 年 1 月 1 日至今的毫秒数。

Global object wx

wx is a global object of a small program that hosts a small program capability-related API. T he small program development framework provides a wealth of WeChat native APIs, which can easily adjust the capabilities provided by WeChat, such as obtaining user information and understanding network status. You can learn about this wx object in The Console of WeChat Developer Tools.

  1. wx

You can see all the properties and methods of wx, and if you don't know which properties and methods of wx, you can consult the technical documentation.

Technical documentation: API technical documentation

Understand the state of the network

Get technical documentation for network type: wx.getNetworkType().

You can switch between the developer tool simulator networks and then enter the following code multiple times in the console to see what the difference is:

  1. wx.getNetworkType({
  2. success(res) {
  3. console.log(res)
  4. }
  5. });

Learn about users

Get user information technology documentation: wx.getUserInfo().

After logging into the developer tool (everyone should already be logged in), enter the following code in the console console to see what information you can get:

  1. wx.getUserInfo({
  2. success(res) {
  3. console.log(res);
  4. }
  5. });

Then exit the developer tool and enter the code above to see what exciting results are?

Get device information

Get device information technology documentation: wx.getSystemInfo().

  1. wx.getSystemInfo({
  2. success (res) {
  3. console.log(res.model)
  4. console.log(res.pixelRatio)
  5. console.log(res.windowWidth)
  6. console.log(res.windowHeight)
  7. console.log(res.language)
  8. console.log(res.version)
  9. console.log(res.platform)
  10. }
  11. })

The page link jumps

Page Jump Technical Documentation: wx.navigateTo().

In addition to getting information about users, devices, networks, and so on, methods that use the console to call objects can also perform actions, such as page jumps. Enter in console Console:

  1. wx.navigateTo({
  2. url: '/pages/home/imgshow/imgshow'
  3. })

You can also go back to the top level of the page and enter it in the console

The page returns technical documentation: wx.navigateBack().

  1. wx.navigateBack({
  2. delta: 1
  3. })

Displays a message prompt box

Display message prompt box technical documentation: wx.showToast().

  1. wx.showToast({
  2. title: '弹出成功',
  3. icon: 'success',
  4. duration: 1000
  5. })

Set the title of the current page

Set the title technical documentation: wx.setNavigationBarTitle().

  1. wx.setNavigationBarTitle({
  2. title: '控制台更新的标题'
  3. })

Open the file selection

Open the file selection technical documentation: wx.chooseImage().

  1. wx.chooseImage({
  2. count: 1,
  3. sizeType: ['original', 'compressed'],
  4. sourceType: ['album', 'camera'],
  5. success (res) {
  6. const tempFilePaths = res.tempFilePaths
  7. }
  8. })

This part is mainly to let everyone understand the power of console Console, and through the console real-world approach to the operation of the small program API has a preliminary understanding.