JS 常用

String对象
charAt()      返回指定索引的位置的字符 

indexOf()      从前向后检索字符串,看是否含有指定字符串

lastIndexOf()   从后向前检索字符串,看是否含有指定字符串

concat()      连接两个或多个字符串  s1.concat(s2) 

match()        使用正则表达式模式对字符串执行查找,并将包含查找结果最为结果返回

replace()     替换一个与正则表达式匹配的子串

search()      检索字符串中与正则表达式匹配的子串。如果没有找到匹配,则返回 -1。 

slice(start,end)     根据下标截取子串 

substring(start,end) 根据下标截取子串 

split()           根据指定分隔符将字符串分割成多个子串,并返回数组

substr(start,length)  根据长度截取字符串 *

toUpperCase()       返回一个字符串,该字符串中的所有字母都被转化为大写字母。 

toLowerCase()       返回一个字符串,该字符串中的所有字母都被转化为小写字母。

trim()    				去掉字符串前后空格(ES5)

startsWith() 			字符串是否以某个字符开头(ES6)

endsWith() 				字符串是否以某个字符结尾(ES6)

includes() 				字符串是否包含某个字符(ES6)

repeat() 				重复某个字符串几次(ES6
slice() : 它的第一个参数是子字符串的开始位置,第二个参数是子字符串的           结束位置(不含该位置)
'JavaScript'.slice(0, 4) // "Java"
substr() :方法的第一个参数是子字符串的开始位置(从0开始计算),第二个		  参数是子字符串的长度。
'JavaScript'.substr(4, 6) // "Script"
replace() :用于替换匹配的子字符串,一般情况下只替换第一个匹配(除非使用带有g修饰符的正则表达式)
'aaa'.replace('a', 'b') // "baa"
split():方法按照给定规则分割字符串,返回一个由分割出来的子字符串组成的数组
'a|b|c'.split('|') // ["a", "b", "c"]


Array对象中常用方法:
concat()    表示把几个数组合并成一个数组 
['hello'].concat(['world'])

join()     设置指定参数为分隔符,连接数组元素为一个字符串返回
                不提供参数,默认逗号分隔

pop()        移除数组最后一个元素,并返回该元素,会改变原数组

shift()      移除数组中第一个元素 并返回该元素,会改变原数组

slice(start,end) 返回提取的数组中的一段 从0开始
第一个参数为起始位置,第二个参数为终止位置,省略第二个参数将一直返回到最后

splice()  可以用来删除,可以用来插入,也可以用来替换 
第一个参数是删除的起始位置(从0开始),第二个参数是被删除的元素个数。如果后面还有更多的参数,则表示这些就是要被插入数组的新元素。


push()       往数组最后添加一个元素,返回最新长度,会改变原数组

unshift()      往数组第一个位置添加一个元素,返回最新长度,会改变原数组 可以是多个参数

sort()      对数组进行排序 
                 [10111, 1101, 111].sort(function (a, b) {
                  return a - b;
                 })

reverse()    方法用于颠倒排列数组元素 ,返回改变后的数组

map()       将数组的所有成员依次传入参数函数,然后把每一次的执行结果组成一个新数组返回。
                var numbers = [1, 2, 3];
                numbers.map(function (n) {
                  return n + 1;
                });
                // [2, 3, 4]
                
toLocaleString()   把数组转换为本地字符串

array对象属性: 

    length       表示取得当前数组长度 (常用)

    constructor     引用数组对象的构造函数

    prototype     通过增加属性和方法扩展数组定义
forEach():
let arr=[1, 2, 3] let a=[]
arr.forEach(item => {  //item当前值
    item + 1
    a.push(item)
})

filter():方法用于过滤数组成员,满足条件的成员组成一个新数组返回
let arr = [1,2,3].filter(item=>{
    return item<2
})
some() :只要其中一个成员满足条件,中止遍历,并返回 true
[1,2,3].some(item=>{
    return item=2
})
every() :所有成员都满足条件,才会返回 true
[1,2,3].every(item=>{
    return item < 5
})
indexOf():返回指定元素在数组中第一次出现的位置,没有出现返回 -1
		  第二个参数表示开始搜索的位置
let a=['a','c']
a.indexOf('b') // -1
a.indexOf('a',2) //-1
lastIndexOf(): 返回最后一次出现的位置, 没有出现返回 -1
map (): 方法创建一个新数组,其结果是该数组中的每个元素都调用一次提供的函数后的返回值。

var arry = [1,2,3]
var ary = arry.map(item + 1)

console.log(ary) // [2,3,4]
遍历数组的方法特性:
ES5:
forEach() filter() reduce() map() some() every 
都会跳过空位 arr= [,1,,2]  但是会保留这个值

ES6: 
都会将空位当做 undefined


reduce() : 将多个值累积  
参数: 
1.Accumulator (acc) (累计器)
2.Current Value (cur) (当前值)
3.Current Index (idx) (当前索引)
4.Source Array (src) (源数组)

数组求和:
let arry = [20,52,13,1].reduce((acc, cur)=> acc + cur)

求积:
let arry = [20,10,10,1].reduce((acc, cur)=> acc * cur)


累加数组中对象的值:

要累加对象数组中包含的值,必须提供初始值,以便各个item正确通过你的函数。
// 数组对象
let initVal = 0;  // 添加初始值
let arrObj = [
    {age: 20},
    {age: 20},
    {age: 20},
    {age: 1}
]. reduce((acc,cur) => acc + cur.age, initVal)
console.log(arrObj);   


对象去重  arr 数组, key 关键字 
    arrRemoveRepeat(arr, key) {
      let obj = {};
      arr = arr.reduce(function(item, next) {
        obj[next[key]] ? "" : (obj[next[key]] = true && item.push(next));
        return item;
      }, []);
      return arr;
    },

对象判断有无空值
 const empty = Object.values(data).filter(val => val == '')
 if(empty.length > 0) return

正则表达式:

有一段代码:截取其中css代码
data='<html>
      <title>截取</title>
     <style>
      html{
      background:red;
      color:#fff;
     }
    </style>
    </html>
'
let str=/<style>(\S*)<\/style>/

改变this指向:

call() :指定 this 的指向
    参数应该是一个对象 ,如果参数为 空 ,nullundefined ,	       则会默认的传入全局对象

        var n = 123;
        var obj = { n: 456 };
        function a() {
          console.log(this.n);
        }
        a.call() // 123
        a.call(null) // 123
        a.call(undefined) // 123
        a.call(window) // 123
        a.call(obj) // 456

    如果call方法的参数是一个原始值,那么这个原始值会自动转成对应的包装对象,然后传入call方法。

call方法还可以接受多个参数。
	call的第一个参数就是this所要指向的那个对象,后面的参数则是函数调	用时所需的参数。
    function add(a, b) {
  	 return a + b;
    }

    add.call(this, 1, 2) // 3

apply() :改变 this 指向 ,参数是数组
func.apply(thisValue, [arg1, arg2, ...])
   	function f(x, y){
  		console.log(x + y);
    }

    f.call(null, 1, 1) // 2
    f.apply(null, [1, 1]) // 2        
找出数组最大值、最小值
	var a = [10, 2, 4, 15, 9];
	Math.max.apply(null, a) // 15
bind :this 的对象赋值,一定要注意this指向的改变
       将函数体内的this绑定到某个对象,然后返回一个新函数。
    var d = new Date();
    d.getTime() // 1481869925657

    var print = d.getTime;
    print() // Uncaught TypeError: this is not a Date object.
	//getTime内部的this指向Date的实例,赋值给 print 指向改变
解决:
var print = d.getTime.bind(d);
print() // 1481869925657this绑定到d对象
	
如果 bind 指向是 null 或者 undefined 则代表指向全局对象 window
	let x=5
	function add(y) {
 	 return this.x + y;
    }
    var plus5 = add.bind(null,10);
    plus5() //15

search 转对象
  const  SearchUrlJson = (search) => {
    if (search) {
        if (search.indexOf('?') == 0) {
            search = search.substring(1);
    }
    return JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g, '":"') + '"}', function(key, value) {
        return key === "" ? value : decodeURIComponent(value)
    });
    }
    return {};
  }


对象转json
  const toQueryPair = (key, value) => {
    if (typeof value === 'undefined') {
      return `&${key}=`
    }
    return `&${key}=${value}`
  }
  const objToParam = (param) => {
    if (Object.prototype.toString.call(param) !== '[object Object]') {
      return ''
    }
    let queryParam = ''
    for (const key in param) {
      if (param.hasOwnProperty(key)) {
        if (param[key]) {
          console.log(key)
          const value = param[key]
          queryParam += toQueryPair(key, value)
        }
      }
    }
    return queryParam
  }

// 深克隆对象/数组
export const deepClone = obj => {
  let ret
  if (isPlainObject(obj)) {
    ret = {}
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        const attrValue = obj[key]
        if (isPlainObject(attrValue) || isArray(attrValue)) {
          ret[key] = deepClone(attrValue)
        } else {
          ret[key] = attrValue
        }
      }
    }
  } else if (isArray(obj)) {
    ret = []
    for (let val of obj) {
      if (isArray(val) || isPlainObject(val)) {
        ret.push(deepClone(val))
      } else {
        ret.push(val)
      }
    }
  }

  return ret
}




/**
 * 获取查询参数
 * @returns {*}
 */
export const parseURL = () => {
  const urlSegment = window.location.href.split('?')
  const query =  urlSegment.length > 1 ? querystring.parse(urlSegment[1]) : {}
  return {
    path: urlSegment[0],
    query
  }
}

/**
 * 根据path和查询参数,生成完整URL
 * @param path
 * @param query
 * @returns {*}
 */
export const createQueryPath = (path, query) => {
  const queryStr = querystring.stringify(query)
  if (queryStr) {
    return `${path}?${queryStr}`
  }
  return path
}


// 对象去重
export const arrRemoveRepeat= (arr, key) =>{
  let obj = {};
  arr = arr.reduce(function(item, next) {
    obj[next[key]] ? "" : (obj[next[key]] = true && item.push(next));
    return item;
  }, []);
  return arr;
}

// 对象判断是否为空
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值