JavaScript basic packaging type String (string object)

JavaScript basic packaging type String (string object)

Only objects and complex data types have properties and methods. Why does the simple data type string have a length property?

Basic packaging type: packaging simple data types into complex data types

What are the basic packaging types?
Insert picture description here

var str='pink';
console.log(str.length); //4

The above code is equivalent to

var str=new String('pink');
console.log(str.length); //4
  1. Return position according to the character
    str.indexOf(' character to be searched',[starting position]) The
    second parameter can be omitted
var str='pink';
console.log(str.indexOf('n')); //2
  1. According to the character return position
    str.lastIndexOf() search from back to front
var str='pinkner';
console.log(str.lastIndexOf('n')); //4
  1. Returns the character
    str.charAt (index number) according to the position
var str4 = 'andy';
console.log(str4.charAt(3));  //'y'
  1. Returns the character according to the position
    str.charCodeAt (index number) returns the ASCII value of the character (you can judge which key the user pressed)
var str4 = 'andy';
console.log(str4.charCodeAt(0));  //97(a的ASCII值是97)

Case: Given a string,'abaasdffggghhjjkkgfddsssss3444343'

  1. String length
  2. Take out the character at the specified position, such as 0,3,5,9
  3. Find whether the specified character exists in the given string, such as i, c, b
  4. Replace the specified characters, such as g is replaced by 22, ss is replaced by b
  5. Intercept the character string from the specified start position to the end position, such as from 1 to 5
  6. Find the most frequent characters and the number of occurrences in a given string
var str11 = 'abaasdffggghhjjkkgfddsssss3444343';
        //第一问
console.log(str11.length);
        //第二问
console.log(str11.charAt(0));
console.log(str11.charAt(3));
console.log(str11.charAt(5));
console.log(str11.charAt(9));
        //第三问
var num = str11.indexOf('i');
if (num == -1) {
      console.log('不存在');
} else {
      console.log('存在');
}
        //第四问
while(str11.indexOf('g')!=-1){
      str11=str11.replace('g','22');
 }
 console.log(str11);
        //第五问
 console.log(str11.substr(0, 5));
        //第六问 找出给定字符串中出现次数最多的字符及出现次数
 var str11 = 'abaasdffggghhjjkkgfddsssss3444343';
 var O = {};
 for (var i = 0; i < str11.length; i++) {
        var chars1 = str11.charAt(i);
        if (O[chars1]) {
                O[chars1]++;
        } else {
                O[chars1] = 1;
        }
}
var Max = 0;
for (var key in O) {
      if (Max < O[key]) {
           Max = O[key];
           var ch1 = key;
      }
}
console.log('出现次数最多的字符是' + ch1 + ',' + '出现了' + Max + '次');

Guess you like

Origin blog.csdn.net/Angela_Connie/article/details/110308129