Detailed explanation of JavaScript data types (string, array)

This article will introduce two commonly used data types in JavaScript - string and array , just follow me

1. String

In fact, the use of strings is similar, there is no special novelty

1.1, string format

  • Normal strings are wrapped with ' ' (single quotes) or " " (double quotes)
  • escape character please use \
//其实学过编程的基本都能知道这些基本的转义字符

\'				//单引号
\"				//双引号
\\				//反斜杠
\n				//换行
\r				//回车
\t				//水平制表符

If you want to write a long string, you can use `` in the outer layer (that is, the key above the table key and below the ESC key)

var str_1 = "Hello world!";
console.log("str_1 = " + str_1);				//输出 Hello world!
var str_2 = 'Hello world!';
console.log("str_2 = " + str_2);				//输出 Hello world!
var str_3 = "\'Hello world!\'";
console.log("str_3 = " + str_3);				//输出 'Hello world!'
var str_4 = "Hello \nworld!";
console.log("str_4 = " + str_4);				/* 输出  Hello
                                  				world!*/
// str_5 是一个使用 `` 包裹的长字符串
var str_5 = `Today is a
        nice
        day吧
        !`;
console.log("str_5 = " + str_5);				/* 输出 Today is a
                                            			nice
                                            			day
                                            			!` */

Console output:

6



If we need to connect strings, we can use the + sign to connect, and ES6 has added a new method by using $ and ``

//下面我们演示两种连接字符串的方式

var str_6 = "Hello";
var str_7 = " world";
console.log("(+ 号连接)str_6 + str_7 = " + str_6 + str_7 + "!");
//请注意 ` 需要转义字符才能显示哦
console.log(`($ 和 \`\` 连接)str_6 + str_7 = ${
      
      str_6}${
      
      str_7}!`);

Browser console output:

7

Note: Strings in JavaScript are immutable . This is the same as Java. Some people may think that we can splice strings. In fact, the memory address of the spliced ​​string is no longer the original string address!

In the following example, we try to change Hello to hello, but the output is still Hello:

8



1.2. Common methods of strings

1. Case conversion: toUpperCase() & toLowerCase()

//toUpperCase(): string;
//toLowerCase(): string;

var str_8 = "BIG";
console.log("str_8 = " + str_8.toLowerCase());	//输出 big
var str_9 = "small";
console.log("str_9 = " + str_9.toUpperCase());	//输出 SMALL

2. Obtain the subscript of the specified character in the string: indexOf()

//indexOf(searchString: string, position?: number): number;

var str_10 = "This is a test sentence";
console.log("str_10 = " + str_10.indexOf("t"));	//输出 10(可以看出是严格区分大小写的)

3. Intercept substring method 1: substr()

//substr(from: number, length?: number): string;

var str_11 = "Today is Monday!";
console.log("str_11 = " + str_11.substr(9, 6));	//输出 Monday

4. Intercept substring method 2: subString()

//substring(start: number, end?: number): string;

var str_12 = "HaHa, you are funny"
console.log("str_12 = " + str_12.substring(6, 19));//输出 you are funny

The result of running all the above codes:

9


Some people may ask, why is there no length ? Because this is a property of a string, the method is enclosed in brackets (), don't make a mistake!



2. Array

2.1, array format

JavaScript array features: an array can contain any type of data , which is similar to python's list

//数组的创建有多种方式

//1、直接赋值
let array_1 = [1, 2, 3, 'abc', null];

//2、使用 new 关键字(不推荐)
let array_2 = new Array(1, 2, 3, 'abc', null);

You can also use multidimensional arrays

let array_double = [[1, 2], [3, 4], ['5', '6']];
console.log(array_double);

The browser console outputs a two-dimensional array (explain here: Array (2) in the first line means that the first element of the array is also an array, and contains two elements, the value of the element with subscript 0 is 1, and the value of The value of the element marked 1 is 2, and so on below):

10



2.2. Common methods of arrays

First we prepare the test data:

// 我们会使用 array 数组测试常用的方法
var obj = {
    
    
    name: "Mike",
    age: 21,
    school: "清华大学"
};
var arr = ["Hello World!"];
function func1() {
    
    
    console.log("Today is a good day!");
}

//可以看到这个数组的元素类型很多,有 number、字符串、对象、数组和函数,请注意函数写入数组不要使用 (),否则会直接执行(一般情况下没人会把函数写到数组内)
var array = [1, 2, "a", 'b', obj, arr, func1];

1. The length of the array: length (note that this is an attribute, not a method)

//1、数组的长度
console.log("array 数组的长度是:" + array.length);		              //输出 7

Note: If you assign a value to array.length, the longer part will be assigned as undefined, and the shorter part will discard the original elements of the array


2. Obtain the subscript of the array element: indexOf()

//2、获取指定元素在数组中的下标,不存在返回 -1
console.log("元素 3 在 array 数组的下标是:" + array.indexOf(3));         //下标为 -1
console.log("元素 obj 在 array 数组的下标是:" + array.indexOf(obj));     //下标为 4

3. Intercept part of the array: slice()

/* 3、截取数组的一部分
需要注意第一个参数代表开始截取的元素下标,第二个参数代表结束截取的元素下标 + 1
例如:你想要截取下标为 2~3 的数组片段,你得写 slice(2, 4) */

console.log("截取 array 数组下标为 3~5 的元素 ↓↓↓");
console.log(array.slice(3, 6));	                                   
//截取的数组片段为 ['b', obj, arr]

4. Add/pop up elements at the beginning and end: push(), pop(), unshift(), shift()

console.log("\n注意下面输出的内容都是数组的长度!\n");

//4、尾部添加元素:push(),函数返回添加后数组的长度
console.log("array 尾部添加元素 \'10\':" + array.push('10'));	       
//现在数组为:[1, 2, "a", 'b', obj, arr, func1, '10']

//5、尾部弹出数据:pop(),函数返回添加后数组的长度
console.log("array 尾部弹出元素:" + array.pop());		               
//现在数组为:[1, 2, "a", 'b', obj, arr, func1]

//6、头部添加元素:unshift(),函数返回添加后数组的长度
console.log("array 头部添加元素 0:" + array.unshift(0));       
//现在数组为:[0, 1, 2, "a", 'b', obj, arr, func1]

//7、弹出头部元素:shift(),函数返回添加后数组的长度
console.log("array 头部弹出元素:" + array.shift());		            
//现在数组为:[1, 2, "a", 'b', obj, arr, func1]

5. Array sorting: sort()

//8、数组排序:sort()
var array_2 = [1, 4, 2, 6, 10];
console.log("array_2 数组排序结果:" + array_2.sort());     //输出 [1, 10, 2, 4, 6]

You can see that the array sorting is still compared according to the ASCII code of the characters, so 10 < 2


6. Array element reversal: reverse()

//9、数组元素反转:reverse()
console.log("array_2 数组反转:" + array_2.reverse());    //输出 [6, 4, 2, 10, 1]

7. Connector: join

//10、连接符:join
console.log("使用 join 连接 array_2 数组元素:" + array_2.join(" -- "));  //输出 6 -- 4 -- 2 -- 10 -- 1

The output results of all the test methods above (all marked, how good for you):

11


So let’s talk about strings and arrays. The above methods are more commonly used. More methods suggest CTRL + left mouse button (for IDEA), click on the String or Array source code to see directly, pay attention to the initials here it's capitalized

Guess you like

Origin blog.csdn.net/qq_52174675/article/details/122594908