js foundation --- built-in object (String)

var str = 'andy'; 
console.log(str.length); 

//相当于以下代码
// 1. 生成临时变量,把简单类型包装为复杂数据类型 
var temp = new String('andy'); 
// 2. 赋值给我们声明的字符变量 
str = temp; 
// 3. 销毁临时变量 
temp = null;

1. Strings are immutable

It means that the value inside is immutable. Although it seems that the content can be changed, the address is actually changed and a new memory space is opened in the memory.

var str='小明';
console.log(str);//小明
str='小新';
console.log(str);//小新

Insert picture description here

2. Related methods

Insert picture description here

Case 1: Find the number of occurrences of a character in a string
Thoughts:
① Core algorithm: first find the position where the first o appears
② Then as long as the result returned by indexOf is not -1, continue to look up
③ Because indexOf can only be found The first one, so the following search uses the second parameter, and the current index is increased by 1, so as to continue the search

var str = 'absodjogokoroy';
 var count = 0;
 var index = str.indexOf('o'); //o第一次出现的索引位置
 while (index != -1) {
    
    
     console.log(index); //
     count++;
     index = str.indexOf('o', index + 1);

 }
 console.log(count);

Insert picture description here
Case 2: Count the characters and times that appear the most.
Thoughts:
① Core algorithm: traverse this string using charAt()
② Store each character in the object. If the object does not have this attribute, the attribute value is 1. If it exists, The attribute value is +1
③ Traverse the object to get the maximum value and the character

var str = 'absodjogokoroy';
 var obj = {
    
    };

 for (var i = 0; i < str.length; i++) {
    
    
     if (obj[str.charAt(i)]) {
    
     //对象中含字母属性
         obj[str.charAt(i)]++;
     } else {
    
     //对象中不含字母属性
         obj[str.charAt(i)] = 1;
     }

 }
 console.log(obj);
 var max = 0;
 var ch = '';
 for (var k in obj) {
    
    
     if (max < obj[k]) {
    
    
         max = obj[k];
         ch = k;
     }
 }
 console.log("出现次数最多的字符是:" + ch + ",次数是:" + max);

Insert picture description here

Guess you like

Origin blog.csdn.net/pilgrim_121/article/details/113064705