js笔记
01.查找指定字符在字符串中出现的位置及次数
<script> var str = 'hahahehexixiheihei',
arr = [], pos = str.indexOf('h'); while(pos > -1){ arr.push(pos); pos = str.indexOf('h', pos + 1); } console.log(arr); // 查找字符在字符串中出现的位置 console.log(arr.length); // 查找字符个数 </script>
例子通过不断增加indexOf()方法开始查找的位置,遍历了一个长字符串。在循环之外,首先找到了要查找的字符"h"在字符串中的初始位置;而进入循环后,则每次都给indexOf()传递上一次的位置加 1。这样,就确保了每次新搜索都从上一次找到的子字符串的后面开始。每次搜索返回的位置依次被保存在数组 pos 中,以便将来使用。
02.正确获取浏览器视图区域大小
<script> var pageWidth = window.innerWidth, pageHeight = window.innerHeight; if (typeof pageWidth != "number"){ if (document.compatMode == "CSS1Compat"){ pageWidth = document.documentElement.clientWidth; pageHeight = document.documentElement.clientHeight; } else { pageWidth = document.body.clientWidth; pageHeight = document.body.clientHeight; } } alert(pageWidth + '---' +pageHeight); </script>
一般浏览器使用window.innerWidth和window.innerHeight就可以获取到浏览器视图区域的大小,没有获取成功时,使用document.compatMode来判断当前浏览器采用的渲染方式是CSS1Compat(标准兼容模式开启)还是BackCompat(标准兼容模式关闭),并分别使用不同的方式获取浏览器视图大小,兼容目前流行的全部浏览器,包括:IE、Firefox、Safari、Opera、Chrome。