js汇总

作者: 裁尘的人儿 | 来源:发表于2020-08-06 13:40 被阅读0次

一、初级常用函数

0. 基本函数

计算字符串的长度:length 属性 
var s = "String 类型长度";  //定义字符串
console.log(s.length);  //返回10个字符

取该字符串的第几位的字符:字符串.charAt(第几位) 

测试是否为数值型:isNaN(变量)

查看变量的类型:typeof x
//typeof是一个运算符,有2种使用方式:
(1)typeof(表达式):该种对表达式做运算
(2)typeof 变量名:该种是对变量做运算。
//typeof的返回值为字符串,值包括如下几种:
// 1. 'undefined'              --未定义的变量或值
// 2. 'boolean'                 --布尔类型的变量或值
// 3. 'string'                     --字符串类型的变量或值
// 4. 'number'                  --数字类型的变量或值
// 5. 'object'                    --对象类型的变量或值,或者null(这个是js历史遗留问题,将null作为object类型处理)
// 6. 'function'                 --函数类型的变量或值


字符转数字:
(1) parseInt
(2) parseFloat

数字转换成字符型:
(1)加空串:""+10  或  10 + ""
(2)括号先计算再转换:(10).toString()
(3)双点解析:10..toString()

字符与字符相连接:使用‘+’号连接

==和===的区别:
(1)“==”:用于比较两个操作数是否相等,这里的相等定义的非常宽松,可zhi以允许进行类型转换
(2)“===”:用来检测两个操作数是否严格相等
注意:
1、对于string,number等基础类型,不同类型间比较,==和===是有区别的,==之比较“转化成同一类型后的值”看“值”是否相等,===如果类型不同,其结果就是不等同类型比较,直接进行“值”比较,两者结果一样
2、对于Array,Object等高级类型,==和===是没有区别的
3、基础类型与高级类型,==和===是有区别的对于==,将高级转化为基础类型,进行“值”比较,因为类型不同,===结果为false


声明变量:var来进行声明

判断语句结构:if(condition){}else{}

循环中止的命令是:break


1. 数学函数(用Math来调用):

Math.abs(x)    返回数的绝对值。
Math.ceil(x)    对小数进行上舍入。
Math.floor(x)    对数进行下舍入。
Math.round(x)    把数四舍五入为最接近的整数。
Math.max(x,y)    返回 x 和 y 中的最高值。
Math.min(x,y)    返回 x 和 y 中的最低值。
Math.pow(x,y)    返回 x 的 y 次幂/方。
Math.sqrt(x)    返回数的平方根。
Math.random()    随机数生成器:返回 0 ~ 1 之间的随机数。
 

2. 对象属性

prototype 属性使您有能力向对象添加属性和方法。

#
#对象的属性valueOf、 toString、 constructor
obj.valueOf()

2.1 Array.prototype

Array.prototype 属性表示 Array 构造函数的原型,并允许您向所有Array对象添加新的属性和方法。

会改变自身的方法

下面的这些方法会改变调用它们的对象自身的值:
Array.prototype.copyWithin()
在数组内部,将一段元素序列拷贝到另一段元素序列上,覆盖原有的值。

Array.prototype.fill()
将数组中指定区间的所有元素的值,都替换成某个固定的值。

Array.prototype.pop()
删除数组的最后一个元素,并返回这个元素。

Array.prototype.push()
在数组的末尾增加一个或多个元素,并返回数组的新长度。

Array.prototype.reverse()
颠倒数组中元素的排列顺序,即原先的第一个变为最后一个,原先的最后一个变为第一个。

Array.prototype.shift()
删除数组的第一个元素,并返回这个元素。

Array.prototype.sort()
对数组元素进行排序,并返回当前数组.

Array.prototype.splice()
在任意的位置给数组添加或删除任意个元素。

Array.prototype.unshift()
在数组的开头增加一个或多个元素,并返回数组的新长度。

不会改变自身的方法

下面的这些方法绝对不会改变调用它们的对象的值,只会返回一个新的数组或者返回一个其它的期望值。

Array.prototype.concat()
返回一个由当前数组和其它若干个数组或者若干个非数组值组合而成的新数组。

Array.prototype.includes()
判断当前数组是否包含某指定的值,如果是返回 `true`,否则返回 `false`。

Array.prototype.join()
连接所有数组元素组成一个字符串。

Array.prototype.slice()
抽取当前数组中的一段元素组合成一个新数组。

Array.prototype.toSource()
返回一个表示当前数组字面量的字符串。遮蔽了原型链上的Object.prototype.toSource() 方法。

Array.prototype.toString()
返回一个由所有数组元素组合而成的字符串。遮蔽了原型链上的 Object.prototype.toString()方法。

Array.prototype.toLocaleString()
返回一个由所有数组元素组合而成的本地化后的字符串。遮蔽了原型链上的Object.prototype.toLocaleString()方法。

Array.prototype.indexOf()
返回数组中第一个与指定值相等的元素的索引,如果找不到这样的元素,则返回 -1。

Array.prototype.lastIndexOf()
返回数组中最后一个(从右边数第一个)与指定值相等的元素的索引,如果找不到这样的元素,则返回 -1。

Array.prototype.forEach() 
forEach为每个元素执行对应的方法

Array.prototype.every()
every()可是检测数组中的每一项是否符合条件

Array.prototype.some()
some()可以检测数组中是否有某一项符合条件

Array.prototype.map()
map()对数组的每个元素进行一定操作(映射)后,会返回一个新的数组

Array.prototype.filter()(传入一个筛选函数,对数组里的每一个元素进行筛选,返回筛选出来的值
该filter()方法创建一个新的匹配过滤条件的数组。
用于测试数组的每个元素,函数的返回值要为true/false。返回true保留元素,否则返回false。
#用法:
#返回数组 ages 中所有元素都大于 18 的元素:
#var ages = [32, 33, 16, 40];

#function checkAdult(age) {
#    return age >= 18;
#}
#ages.filter(checkAdult);

Array.prototype.reduce()
reduce()可以实现一个累加器的功能,将数组的每个值(从左到右)将其降低到一个值。

Array.prototype.reduceRight()
 reduceRight的语法以及回调函数的规则和reduce方法是一样的,区别就是在与reduce是升序,即角标从0开始,而reduceRight是降序,即角标从arr.length-1开始。(方法可应用于字符串。)

补:  .isArray()
isArray()是Array对象的一个静态函数,用来判断一个对象是不是数组



1. Array.prototype.indexOf
indexOf()方法返回在该数组中第一个找到的元素位置,如果它不存在则返回-1。

# 使用for:
# var arr = ['apple','orange','pear'],
#     found = false;
# for(var i= 0, l = arr.length; i< l; i++){
#     if(arr[i] === 'orange'){
#         found = true;
#     }
# }
# console.log("found:",found);

# 使用indexOf:
# var arr = ['apple','orange','pear'];  
# console.log("found:", arr.indexOf("orange") != -1);

2、Array.prototype.lastindexOf
lastIndexOf() 方法返回在该数组中最后一个找到的元素位置,和 indexof相反。

3、Array.prototype.every()
every()可是检测数组中的每一项是否符合条件

# 使用for:
# 
# 是否全部大于0
# 
# var ary = [12,23,24,42,1];
# var result = function(){
#   for (var i = 0; i < ary.length; i++) {
#     if(ary[i] < 0){
#        return false;
#     }
#   }
#   return true; //需全部满足
# }
# console.log(result()) //全部满足,返回true

# 使用every:
# var ary = [12,23,24,42,1];
# var result = ary.every(function(item, index){
#   return item > 0
# })
# console.log(result)

4、Array.prototype.some()
some()可以检测数组中是否有某一项符合条件
# 使用for:
# 
# 是否存在小于0的项
# 
# var ary = [12,23,-24,42,1];
# var result = function(){
#   for (var i = 0; i < ary.length; i++) {
#     if(ary[i] < 0){
#        return true;
#     }
#   }
#   return false; //只需满足一个
# }
# console.log(result())  //有一项小于0,返回true

# 使用some:
# var ary = [12,23,-24,42,1];
# var result = ary.some(function(item, index){
#   return item < 0
# })
# console.log(result)


5、 Array.prototype.forEach() 
forEach为每个元素执行对应的方法
#使用for:
# var arr = [1,2,3,4,5,6,7,8];

# for(var i= 0, l = arr.length; i< l; i++){
# console.log(arr[i]);
# }

# 使用forEach():
# var arr = [1,2,3,4,5,6,7,8];

# arr.forEach(function(item,index){
# console.log(item);
# });
# forEach是用来替换for循环的


6、 Array.prototype.map()
map()对数组的每个元素进行一定操作(映射)后,会返回一个新的数组, 

# 使用for:
# var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];

# function getNewArr(){
#   var newArr = [];
#   for(var i= 0, l = oldArr.length; i< l; i++){
#     var item = oldArr[i];
#     item.full_name = [item.first_name,item.last_name].join(" ");
#     newArr[i] = item;
#   }
#   return newArr;
# }
# console.log(getNewArr());

# 使用map:
# var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];

# function getNewArr(){
#   return oldArr.map(function(item,index){
#     item.full_name = [item.first_name,item.last_name].join(" ");
#     return item;
#   });

# }
# console.log(getNewArr());
# map()是处理服务器返回数据时是一个非常实用的函数。

forEach 与map的区别:

语法:forEach和map都支持2个参数:一个是回调函数(item,index,list)和上下文;

forEach:用来遍历数组中的每一项;这个方法执行是没有返回值的,对原来数组也没有影响;数组中有几项,那么传递进去的匿名回调函数就需要执行几次;每一次执行匿名函数的时候,还给其传递了三个参数值:数组中的当前项item,当前项的索引index,原始数组list;理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是我们可以自己通过数组的索引来修改原来的数组;

forEach方法中的this是ary,匿名回调函数中的this默认是window;
#var ary = [12,23,24,42,1];
# var res = ary.forEach(function (item,index,input) {
#   input[index] = item*10;
# })
# console.log(res);//-->undefined;
# console.log(ary);//-->会对原来的数组产生改变;

map: 和forEach非常相似,都是用来遍历数组中的每一项值的,用来遍历数组中的每一项;

区别:map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);

不管是forEach还是map 都支持第二个参数值,第二个参数的意思是把匿名回调函数中的this进行修改。
# var ary = [12,23,24,42,1];
# var res = ary.map(function (item,index,input) {
#   return item*10;
# })
# console.log(res);//-->[120,230,240,420,10];
# console.log(ary);//-->[12,23,24,42,1];

7、 Array.prototype.filter
该filter()方法创建一个新的匹配过滤条件的数组。
# 使用for:
# var arr = [
#   {"name":"apple", "count": 2},
#   {"name":"orange", "count": 5},
#   {"name":"pear", "count": 3},
#   {"name":"orange", "count": 16},
# ];
# var newArr = [];
# for(var i= 0, l = arr.length; i< l; i++){
#   if(arr[i].name === "orange" ){
#     newArr.push(arr[i]);
#   }
# }
# console.log("Filter results:",newArr);

# 使用 filter():
# var arr = [
#   {"name":"apple", "count": 2},
#   {"name":"orange", "count": 5},
#   {"name":"pear", "count": 3},
#   {"name":"orange", "count": 16},
# ];
# var newArr = arr.filter(function(item){
#   return item.name === "orange";
# });
# console.log("Filter results:",newArr);



8、 Array.prototype.reduce()
reduce()可以实现一个累加器的功能,将数组的每个值(从左到右)将其降低到一个值。 说实话刚开始理解这句话有点难度,它太抽象了。 

场景: 统计一个数组中有多少个不重复的单词 
# 使用for:
# var arr = ["apple","orange","apple","orange","pear","orange"];

# function getWordCnt(){
#   var obj = {};
#   for(var i= 0, l = arr.length; i< l; i++){
#     var item = arr[i];
#     obj[item] = (obj[item] +1 ) || 1;
#   }
#   return obj;
# }
# console.log(getWordCnt());


让我先解释一下我自己对reduce的理解。reduce(callback, initialValue)会传入两个变量。回调函数(callback)和初始值(initialValue)。假设函数它有个传入参数,prev和next,index和array。prev和next你是必须要了解的。一般来讲prev是从数组中第一个元素开始的,next是第二个元素。但是当你传入初始值(initialValue)后,第一个prev将是initivalValue,next将是数组中的第一个元素。 

/* 
* 二者的区别,在console中运行一下即可知晓
*/
# var arr = ["apple","orange"];

# function noPassValue(){
#   return arr.reduce(function(prev,next){
#     console.log("prev:",prev);
#     console.log("next:",next);
#     return prev + " " +next;
#   });
# }
# function passValue(){
#   return arr.reduce(function(prev,next){
#     console.log("prev:",prev);
#     console.log("next:",next);
#     prev[next] = 1;
#     return prev;
#   },{});
# }

# console.log("No Additional parameter:",noPassValue());
# console.log("----------------");
# console.log("With {} as an additional parameter:",passValue());

9.Array.prototype.reduceRight()
 reduceRight的语法以及回调函数的规则和reduce方法是一样的,区别就是在与reduce是升序,即角标从0开始,而reduceRight是降序,即角标从arr.length-1开始。

方法可应用于字符串。

/* 
* 使用此方法反转字符串中的字符
*/
# var word = "retupmoc";
# function AppendToArray(previousValue, currentValue) {
#   return previousValue + currentValue;
# }
# var result = [].reduceRight.call(word, AppendToArray, "the ");
# console.log(result); // the computer

补.isArray()
isArray()是Array对象的一个静态函数,用来判断一个对象是不是数组

# var ary1 = [];
# var res1 = Array.isArray(ary1);  // Output: true
# console.log(res1)

# var ary2 = new Array();
# var res2 = Array.isArray(ary2);  // Output: true
# console.log(res2)

# var ary3 = [1, 2, 3];
# var res3 = Array.isArray(ary3);  // Output: true
# console.log(res3)

# var ary4 = new Date();
# var res4 = Array.isArray(ary4);  // Output: false
# console.log(res4)

3. html页面系统函数

window.location.reload() #刷新当前页面

parent.location.reload() #刷新父亲对象(用于框架)
opener.location.reload() #刷新父窗口对象(用于单开窗口)
top.location.reload() #刷新最顶端对象(用于多开窗口)

window.history.back() #返回上一页
window.history.forward() #返回下一页
window.history.go(返回第几页,也可以使用访问过的URL)


document.write("") #不换行的输出
//document.write(Math.pow(-2,4) + "<br />")
document.writeln() #换行输出


document.body.noWrap=true //防止链接文字折行.


document.close() #关闭文档的输出流



关于窗口:
(1)打开窗口:window.open()
(2)关闭一个窗口:window.close()
(3)窗口本身:self
* 默认开启新窗口:
        <input type="button" value="开启百度(新窗口)" onclick="window.open('http://www.baidu.com');" />
* 在当前窗口跳转: '_self'
        <input type="button" value="开启百度(当前窗口)" onclick="window.open('http://www.baidu.com' , '_self');" />
* 跳到新窗口:'_blank'
        <input type="button" value="开启百度(新窗口)" onclick="window.open('http://www.baidu.com' , '_blank');" />
* 跳到父级窗口: '_parent'
        <input type="button" value="开启百度(父窗口)" onclick="window.open('http://www.baidu.com' , '_parent');" />
* 跳到顶级窗口:'_top'
        <input type="button" value="开启百度(顶级窗口)" onclick="window.open('http://www.baidu.com' , '_top');" />
        


状态栏的设置:
window.status="字符"

弹出提示信息:
window.alert("字符")

弹出确认框:
window.confirm()

弹出输入提示框:
window.prompt();

指定当前显示链接的位置:
window.location.href="URL"

取出窗体中的所有表单的数量:
document.forms.length

关闭文档的输出流:
document.close()

字符串追加连接符:+=

创建一个文档元素:
document.createElement()
document.createTextNode()

得到元素的方法:
document.getElementById()

设置表单中所有文本型的成员的值为空:
<pre>var form = window.document.forms[0]
for (var i = 0; i<form.elements.length;i++){
     if (form.elements[i].type == "text"){
         form.elements[i].value = "";
     }
}</pre>

window.location的属性: 
(1) protocol(http:)
(2) hostname(www.example.com)
(3) port(80)
(4) host(www.example.com:80)
(5) pathname("/a/a.html")
(6) hash("#giantGizmo",指跳转到相应的锚记)
(7) href(全部的信息)


当窗体第一次调用时使用的文件句柄:
onload()

当窗体关闭时调用的文件句柄:
onunload()

设置时间间隔:
setInterval("expr",msecDelay)或
setInterval(funcRef,msecDelay)或
setTimeout

窗口滚动到位置:
window.scrollby

提示输入框:
window.prompt("message","defaultReply");

窗口滚动条:
window.scroll(x,y)

窗口重定向:
window.navigate("http://www.sina.com.cn")

打印:
window.print()

JS中的self指的是当前的窗口

关闭当前的窗口:
window.close()

添加到收藏夹:
external.AddFavorite("http://www.xrss.cn","jaskdlf");

//JS中遇到脚本错误时不做任何操作:
window.onerror = doNothing;
//指定错误句柄的语法为:
window.onerror = handleError;

//状态栏文字的设置:
window.status='文字'
//默认的状态栏文字设置:
window.defaultStatus = '文字.';

防止用户对文本框中输入文本:
onfocus="this.blur()"

取出该元素在页面中出现的数量:
document.all.tags("div(或其它HTML标记符)").length

指元素为选中状态:
select()


window.focus()使当前的窗口在所有窗口之前.
window.blur()指失去焦点,与FOCUS()相反

isDisabled判断是否为禁止状态.
disabled设置禁止状态

contentEditable可设置元素是否可被修改;
isContentEditable返回是否可修改的状态

JS中的换行:\n

引用一个文件式的JS:
<script type="text/Javascript" src="aaa.js">
</script>


parent代表父亲对象,top代表最顶端对象

定义日期型变量:
var today = new Date()

日期函数列表:
dateObj.getTime()得到时间,
dateObj.getYear()得到年份,
dateObj.getFullYear()得到四位的年份,
dateObj.getMonth()得到月份,
dateObj.getDate()得到日,
dateObj.getDay()得到日期几,
dateObj.getHours()得到小时,
dateObj.getMinutes()得到分,
dateObj.getSeconds()得到秒,
dateObj.setTime(value)设置时间,
dateObj.setYear(val)设置年,
dateObj.setMonth(val)设置月,
dateObj.setDate(val)设置日,
dateObj.setDay(val)设置星期几,
dateObj.setHours设置小时,
dateObj.setMinutes(val)设置分,
dateObj.setSeconds(val)设置秒 [注意:此日期时间从0开始计]

单选按钮组判断是否被选中也是用checked.

var form = window.document.forms[0]
//取出html页面里所有的forms的第一个

复选按钮在JS中判断是否选中:
(1) document.forms[0].check
(2) this.checked
 (checked属性代表为是否选中返回TRUE或FALSE)

4. 字符串函数

取从第几位到指定长度的字符串:
string.substr(start[,length])

取出字符串中指定起点和终点的子字符串:
stringA.substring(2,6);

取该字符串的第几位的字符/取字符串中指定位置的一个字符:
字符串.charAt(第几位)

返回字符串2在字符串1中出现的位置:
String1.indexOf("String2")!=-1
注意:返回-1则说明没找到.

#(0)字符型转换成数值型:
parseInt()
parseFloat()

//字符串连接
(1)string.concat(string2)
// concat() 方法可以把多个参数添加到指定字符串的尾部。该方法的参数类型和个数没有限制,它会把所有参数都转换为字符串,然后按顺序连接到当前字符串的尾部最后返回连接后的字符串。 
(2)用 '+' 进行连接
(3)a.join("_")


#(1) split:通过将字符串划分成子串,将一个字符串做成一个字符串数组。
var arr1 = a.split("");
//arr1 = [h,e,l,l,o]


#(2)indexOf :  返回字符串中一个子串第一处出现的索引(从左到右搜索)。如果没有匹配项,返回 -1 。
var index1 = a.indexOf("l");
//index1 = 2

#(3) charAt:返回指定位置的字符。
var get_char = a.charAt(0);
//get_char = "h"

#(4)lastIndexOf:返回字符串中一个子串最后一处出现的索引(从右到左搜索),如果没有匹配项,返回 -1 。
var index1 = lastIndexOf('l');
//index1 = 3


#(5)match:检查一个字符串匹配一个正则表达式内容,如果么有匹配返回 null。
var re = new RegExp(/^\w+$/);
var is_alpha1 = a.match(re);
//is_alpha1 = "hello"
var is_alpha2 = b.match(re);
//is_alpha2 = null

#(6)substring:返回字符串的一个子串,传入参数是起始位置和结束位置。
var sub_string2 = a.substring(1,4);
//sub_string2 = "ell"

#(7)substr属性:返回字符串的一个子串,传入参数是起始位置和长度
var sub_string1 = a.substr(1);
//sub_string1 = "ello"
var sub_string2 = a.substr(1,4);
//sub_string2 = "ello"

#(8)replace属性:替换字符串,第一个参数代表被替换的字符串,第二个参数代表替换的字符串
a.replace("he","aa")

#(9)length 属性 :返回字符串的长度,所谓字符串的长度是指其包含的字符的个数。


#(10)toLowerCase属性:将整个字符串转成小写字母。
var lower_string = a.toLowerCase();
//lower_string = "hello"

#(10)toUpperCase属性:将整个字符串转成大写字母。
var upper_string = a.toUpperCase();
//upper_string = "HELLO"

5. 日期时间函数(需要用变量调用):

var b = new Date(); //获取当前时间
b.getTime() //获取时间戳
b.getFullYear() //获取年份
b.getMonth()+1; //获取月份
b.getDate() //获取天
b.getHours() //获取小时
b.getMinutes() //获取分钟
b.getSeconds() //获取秒数
b.getDay() //获取星期几
b.getMilliseconds() //获取毫秒

window:

代表浏览器中一个打开的窗口。

1. 属性

window.self 引用本窗口window==window.self
window.defaultStatus 缺省的状态条消息,窗口状态栏信息

window.document 当前显示的文档(该属性本身也是一个对象)

window.frame 窗口里的一个框架((FRAME>)(该属性本身也是一个对象)
window.history 窗口的历史列表(该属性本身也是一个对象)

window.length 窗口内的框架数
window.location 窗口所显示文档的完整(绝对)URL地址(该属性本身也是一个对象),设置该属性可打开新的页面
###注意:不要把它与如document.location混淆:
* document.location是当前显示文档的URL。用户不可以改变!!!
* 用户可以改变window.location(用另一个文档取代当前文档),但却不能改变
document.location (因为这是当前显示文档的位置)

window.name 窗口打开时,赋予该窗口的名字

window.opener 代表使用window.open打开当前窗口的脚本所在的窗口(这是Netscape Navigator 3.0beta 3所引入的一个新属性)

window.parent 包含当前框架的窗口的同义词。frame和window对象的一个属性

window.self 当前窗口或框架的同义词

window.status 状态条中的消息

window.top 包含当前框架的最顶层浏览器窗口的同义词

window.window 当前窗口或框架的同义词,与self相同

2.方法:

window.alert() 打开一个Alert消息框

window.clearTimeout() 用来终止setTimeout方法的工作

window.close() 关闭窗口

window.confirm() 打开一个Confirm消息框,用户可以选择OK或Cancel,如果用户单击OK,该方法返回true,单击Cancel返回false

window.blur() 把焦点从指定窗口移开(这是Netscape Navigator 3.0 beta 3引入的新方法)

window.focus() 把指定的窗口带到前台(另一个新方法)

window.open() 打开一个新窗口
window.close() 关闭窗口


window.prompt()键盘输入会话框: 打开一个Prompt对话框,用户可向该框键入文本,并把键入的文本返回到脚本

window.setTimeout() 等待一段指定的毫秒数时间,然后运行指令事件处理程序事件处理程序

window.setIntervel(func, time) 每隔指定时间(毫秒)执行一次操作

window.clearInterval() 清除时间间隔

window.Onload() 页面载入时触发

window.Onunload() 页面关闭时触发

3. 成员对象

window.history:
window.history.length 浏览过的页面数
window.history.back() 后退
window.history.forward() 前进
window.history.go(i) 前进或后退i个页面(i>0前进,i<0后退)


Window.screen:
window.screen.width 屏幕宽度
window.screen.height 屏幕高度
window.screen.colorDepth 屏幕色深
window.screen.availWidth 屏幕可用宽度
window.screen.availHeight 屏幕可用高度(除去任务栏的高度)


Window.navigator:
window.navigator.appCodeName 浏览器代码名
window.navigator.appName 浏览器名
window.navigator.platform 运行浏览器的操作系统平台
window.navigator.appVersion 浏览器的平台和版本
window.navigator.userAgent 由客户机发送服务器的user-agent 头部的值
window.navigator.cookieEnabled 浏览器是否启用cookie
window.navigator.appMinorVersion 浏览器补丁版本
window.navigator.cpuClass cpu类型
Window.navigator.plugins 插件标识
window.navigator.userProfile 用户的个人信息
window.navigator.systemLanguage 客户体系语言
window.navigator.userLanguage 用户语言
window.navigator.onLine 用户是否在线
window.navigator.mimeTypes MIME类型(数组)

document:

代表整个HTML 文档,可用来访问页面中的所有元素。
window和document区别:
1、window 指窗体。document指页面。document是window的一个子对象。
2、用户不能改变 document.location(因为这是当前显示文档的位置)。但是,可以改变window.location (用其它文档取代当前文档)window.location本身也是一个对象, 而document.location不是对象

1. 属性

document.title                 文档标题,等价于HTML的<title>标签
document.bgColor            页面背景色
document.fgColor              前景色(文本颜色)
document.linkColor           未点击过的链接颜色
document.alinkColor            激活链接(焦点在此链接上)的颜色
document.vlinkColor            已点击过的链接颜色
document.URL                   在同一窗口打开另一网页
document.fileCreatedDate       文件建立日期,只读属性
document.fileModifiedDate      文件修改日期,只读属性
document.fileSize              大小,只读属性
document.cookie                设置和读出cookie
document.charset               字符集


2. 方法

document.clear 清除指定文档的内容

document.close 关闭文档流

document.open 打开文档流


document.write() 把文本写入文档,动态向页面写入内容

document.writeln() 把文本写入文档,并以换行符结尾


document.createElement(tag) 创建指定标签的元素

document.getElementById(id)  获得指定id值的元素
  
document.getElementsByName(name)      获得指定Name值的元素


document.alert($(window).height()); //浏览器时下窗口可视区域高度

document.alert($(document).height()); //浏览器时下窗口文档的高度

document.alert($(document.body).height());//浏览器时下窗口文档body的高度

document.alert($(document.body).outerHeight(true));//浏览器时下窗口文档body的总高度 包括border padding margin

document.alert($(window).width()); //浏览器时下窗口可视区域宽度

document.alert($(document).width());//浏览器时下窗口文档对于象宽度

document.alert($(document.body).width());//浏览器时下窗口文档body的高度

document.alert($(document.body).outerWidth(true));//浏览器时下窗口文档body的总宽度 包括border padding margin  

document.alert($(document).scrollTop()); //获取滚动条到顶部的垂直高度

document.alert($(document).scrollLeft()); //获取滚动条到左边的垂直宽度

3. 子对象

(1)body子对象
document.body  文档主体开始和结束,等价于<body></body>
document.body.bgColor          背景颜色
document.body.link             未点击过的链接颜色
document.body.alink          激活链接(焦点在此链接上)的颜色
document.body.vlink      已点击过的链接颜色
document.body.text        文本色
document.body.innerText      <body>...</body>之间的文本
document.body.innerHTML  <body>...</body>之间的HTML代码
document.body.topMargin 页面上边距
document.body.leftMargin      页面左边距
document.body.rightMargin   页面右边距
document.body.bottomMargin  页面下边距
document.body.background    背景
document.body.appendChild(oTag) 添加DOM对象
document.body.οnclick="func()"              鼠标指针单击对象是触发
document.body.οnmοuseοver="func()"    鼠标指针移到对象时触发
document.body.οnmοuseοut="func()"        鼠标指针移出对象时触发


(2)location-位置子对象
document.location.hash  #号后的部分
document.location.host        域名+端口号
document.location.hostname     域名
document.location.href          完整URL
document.location.pathname 目录部分
document.location.port     端口号
document.location.protocol    网络协议
document.location.search      ?号后的部分


(3)通过集合引用(以images集合为例,forms集合等类似)
document.images                <img>标签
document.images.length          <img>标签的个数
document.images[0]             第1个<img>标签       
document.images[i]    

二、高级编码函数:

1. 防抖节流:

防抖

function debounce(func, wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        
        timeout = setTimeout(() => {
            func.apply(context, args)
        }, wait);
    }
}

 

节流

function throttle(func, wait) {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}

 

2. 判断小数是否相等

function epsEqu(x,y) {  
  return Math.abs(x - y) < Math.pow(2, -52);
}

3. || 和 && 的妙用

// 场景 1
function b(a) {
  if (a) {
    return a
  } else {
    return ''
  }
}
// 场景 2
function b(a) {
  return a || ''
}

上面是 || 的用法,也叫做短路处理。常见于 if 条件中,但是他其实也可以直接用于语句中。当第一个参数为 true 就会取第一个参数的值,当第一个参数不为 true 就会取第二个参数的值。&& 正好与 || 相反。第一个参数 为 true 会取第二个参数的值

4. 用对象代替 switch / if

公共内容:
let a = 'VIP'

#场景 1
if (a === 'VIP') {
  return 1
} else if (a === 'SVIP') {
  return 2
}

#场景 2
switch(a) {
  case 'VIP':
    return 1
  case 'SVIP':
    return 2
}

#场景 3: 用对象代替 switch / if
let obj = {
  VIP: 1,
  SVIP: 2
}

这里只是提供了一种方式,具体的使用场景还是要你自己判断。我用的比较多的一个场景是状态映射中文含义,例如支付状态通常获取的是 1, 2,3,4 这种值,但是列表要求显示相应的中文状态 未支付 | 支付中 | 已退款等等

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

相关文章

网友评论

      本文标题:js汇总

      本文链接:https://www.haomeiwen.com/subject/bfryrktx.html