js-常用转换处理方法

1.split("分割条件(正则表达式或者字符)") 字符串 ==> 数组

默认返回数组

(1) 将单词分割为字符

"hello".split("")	//可返回 ["h", "e", "l", "l", "o"]

(2)将句子分割为单词

var words = sentences.split(' ') 

(3)去除字符串中的间隔符号,比如: = | 等

"2:3:4:5".split(":")    //将返回["2", "3", "4", "5"]
"|a|b|c".split("|")    //将返回["", "a", "b", "c"]

 

2.str.charCodeAt(index) 获取字符串对应位置字符的ASCII码(字符串/字符 == > 数字)

比如在hash函数中计算hashcode

 

    function hashFunc(str, max) {
      let hashCode = 0;
      for (let i = 0; i < str.length; i++) {
        // 计算的原理是,字符串的对应位数为多项式的对应n次幂,前面的系数为对应字符的asi2码
        // 取了一个质数31 然后取对应字符的ASII码
        hashCode = 31 * hashcode + str.charCodeAt(i)
      }
    }

 

 

 

 

posted @ 2021-12-23 12:11  嗜血汽车人  阅读(86)  评论(0)    收藏  举报