资源大全

https://my.oschina.net/yomut/blog/755246

注意

涉及 JQuery 用法的参考《JQuery》

替代 eval

1
2
3
4
5
6
7
8
9
//计算表达式的值
function evil(str) {
let Fn = Function; //一个变量指向Function,防止有些前端编译工具报错
return new Fn('return ' + str)();
}

const str = "[{name:'张三'}, {name: '李四', age: 20}]";
const json = evil(str);
console.log(json)

Function

function 函数均有如下内置的方法

callapply可以用来重新定义函数的执行环境,也就是this的指向;callapply都是为了改变某个函数运行时的context,即上下文而存在的,换句话说,就是为了改变函数体内部this的指向

apply

1
Function.apply(obj[, argArray]); //语法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const before = function (fn, beforeFn) {
return function () {
beforeFn.apply(this, arguments)
return fn.apply(this, arguments)
}
}

const after = function (fn, afterFn) {
return function () {
const __ = fn.apply(this, arguments)
afterFn.apply(this, arguments)
return __
}
}

const duck = {
makeVoice: function () {
console.log('我会嘎嘎嘎啦')
},
sleep: function () {
console.log('谁又不会睡觉呢')
},
walk: function () {
console.log('哈哈哈,我会走路啦')
},
init: function () {
this.makeVoice()
this.sleep()
this.walk()
}
}

after(duck.init, function egg () {
console.log('生蛋快乐~')
}).apply(duck) //duck 作为上下文传入

call

1
Function.call(obj[, param1[, param2[, [,...paramN]]]]); // obj 这个对象将代替`Function`类里`this`对象
1
2
3
4
5
6
7
8
9
10
11
12
function Product(name, price) {
this.name = name;
this.price = price;
}

function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}

console.log(new Food('cheese', 5).name);
// expected output: "cheese"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const fun = function ({name, age=19}){
console.log(name, age, this.num) //zhansan 20 100
}

const before = function (fn, beforeFn) {
return function () {
beforeFn.apply(this, arguments)
return fn.apply(this, arguments)
}
}

before(fun, function (){
this.num = 100
}).call(fun, {name:"zhansan", age:20})

bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const module = {
x: 42,
getX: function() {
return this.x;
}
};

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42

集合

Set

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
let mySet = new Set();

mySet.add(1); // Set [ 1 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add("some text"); // Set [ 1, 5, "some text" ]
let o = {a: 1, b: 2};
mySet.add(o);

mySet.add({a: 1, b: 2}); // o 指向的是不同的对象,所以没问题

mySet.has(1); // true
mySet.has(3); // false
mySet.has(5); // true
mySet.has(Math.sqrt(25)); // true
mySet.has("Some Text".toLowerCase()); // true
mySet.has(o); // true

mySet.size; // 5

mySet.delete(5); // true, 从set中移除5
mySet.has(5); // false, 5已经被移除

mySet.size; // 4, 刚刚移除一个值

console.log(mySet);
// logs Set(4) [ 1, "some text", {…}, {…} ] in Firefox
// logs Set(4) { 1, "some text", {…}, {…} } in Chrome

Map

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let myMap = new Map();

let keyObj = {};
let keyFunc = function() {};
let keyString = 'a string';

// 添加键
myMap.set(keyString, "和键'a string'关联的值");
myMap.set(keyObj, "和键keyObj关联的值");
myMap.set(keyFunc, "和键keyFunc关联的值");

myMap.size; // 3

// 读取值
myMap.get(keyString); // "和键'a string'关联的值"
myMap.get(keyObj); // "和键keyObj关联的值"
myMap.get(keyFunc); // "和键keyFunc关联的值"

myMap.get('a string'); // "和键'a string'关联的值"
// 因为keyString === 'a string'
myMap.get({}); // undefined, 因为keyObj !== {}
myMap.get(function() {}); // undefined, 因为keyFunc !== function () {}

基础

typeof - 判断类型

1
2
typeof({}) == "object"
typeof("hello") == "string"

阻止事件冒泡和默认事件

阻止事件冒泡

1
2
3
4
5
6
7
8
9
10
11
function bubbles(e){
var ev = e || window.event;
if(ev && ev.stopPropagation) {
//非IE浏览器
ev.stopPropagation();
} else {
//IE浏览器(IE11以下)
ev.cancelBubble = true;
}
console.log("最底层盒子被点击了")
}

取消默认事件

1
2
3
4
5
6
7
8
9
10
11
function preventDefaultEvent(e){
if(e && e.preventDefault) {
//非IE浏览器
e.preventDefault();
} else {
//IE浏览器(IE11以下)
window.event.returnValue = false;
}

//return false; //或者不写上面的判断直接写这句
}

url 参数解析为 json

1
2
3
4
5
6
7
8
9
10
const parseQueryString = ()=>{
var json = {};
let url = location.href;
var arr = url.substr(url.indexOf('?') + 1).split('&');
arr.forEach(item=>{
var tmp = item.split('=');
json[tmp[0]] = tmp[1];
});
return json;
}

url 参数编码解码

  • encodeURIComponent 编码,对指定参数编码,它可以将参数中的中文、特殊字符进行转义,而不会影响整个 URL

    1
    2
    3
    4
    var a = document.createElement("a");
    a.href = "open360://192.168.0.110:8081/Web/RTSP/index.html?url="+encodeURIComponent("rtsp://admin:hz12345678hz@192.168.0.122:554/Streaming/Channels/101");
    a.innerText='播放';
    document.body.appendChild(a);
  • decodeURIComponent 解码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    const parseQueryString = ()=>{
    var json = {};
    let url = location.href;
    var arr = url.substr(url.indexOf('?') + 1).split('&');
    arr.forEach(item=>{
    var tmp = item.split('=');
    json[tmp[0]] = tmp[1];
    });
    return json;
    }

    var query = parseQueryString();
    let src = decodeURIComponent(query.url);

检测 img src 变化

https://www.manongdao.com/article-1012985.html

1
2
3
4
5
6
$('img').load(function() {
var imageObj = $(this);
if (!(imageObj.width() == 1 && imageObj.height() == 1)) {
console.log('Image source changed');
}
});

监听 input 输入框值变化

  • Jquery

    1
    2
    3
    4
    5
    6
    * onchange 时间又往往是在输入框失去焦点(onblur)时候触发

    * jQuery「**推荐使用**」
    $("#input1").bind("input propertychange",function(event){
    console.log($("#input1").val());
    });
  • JS

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <script type="text/javascript">
    // Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
    function OnInput (event) {
    alert ("The new content: " + event.target.value);
    }
    // Internet Explorer
    function OnPropChanged (event) {
    if (event.propertyName.toLowerCase () == "value") {
    alert ("The new content: " + event.srcElement.value);
    }
    }
    </script>

    <input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" />

打开新页面

  • 能返回到上个页面

    1
    2
    3
    1. window.open(url, "xxx")
    2. window.location.href = url
    3. window.location.assign (url)
  • 不能返回上个页面

    1
    window.location.replace (url)  
  1. History

    1. window.history.back () - 与在浏览器点击后退按钮相同

      1
      window.history.go(-1)
    2. window.history.forward () - 与在浏览器中点击向前按钮相同

      1
      window.history.go(1)
  2. 刷新

    1
    window.location.reload()
  3. 关闭

    1
    window.close();

关闭当前页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function CloseWebPage(){
if (navigator.userAgent.indexOf("MSIE") > 0) {
if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
window.opener = null;
window.close();
} else {
window.open('', '_top');
window.top.close();
}
}
else if (navigator.userAgent.indexOf("Firefox") > 0) {
window.location.href = 'about:blank ';
} else {
window.opener = null;
window.open('', '_self', '');
window.close();
}
}

将变量的值作为key

1
2
3
4
5
6
7
let a = "name";
let b = {
a: "123",
[a]: "456",
[a+"bc"]: "789"
}
// {a: "123", name: "456", namebc: "789"}

对象

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects

Object.keys(obj)

语法

1
Object.keys(obj)

参数

  • obj

    要返回其枚举自身属性的对象

返回值

一个表示给定对象的所有可枚举属性的字符串数组

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// simple array
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array like object with random key ordering
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']

// getFoo is a property which isn't enumerable
var myObj = Object.create({}, {
getFoo: {
value: function () { return this.foo; }
}
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']

Object.values()

语法

1
Object.values(obj)

参数

  • obj

    被返回可枚举属性值的对象

返回值

一个包含对象自身的所有可枚举属性值的数组

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']

// array like object with random key ordering
// when we use numeric keys, the value returned in a numerical order according to the keys
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.values(an_obj)); // ['b', 'c', 'a']

// getFoo is property which isn't enumerable
var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
my_obj.foo = 'bar';
console.log(Object.values(my_obj)); // ['bar']

// non-object argument will be coerced to an object
console.log(Object.values('foo')); // ['f', 'o', 'o']

数组

判断数组中是否包含某元素

1
2
3
4
5
6
let arr = ['liming', 'wangzhe', 'sb'];

arr.indexOf('liming') // 0
arr.indexOf('wangzhe') // 1
arr.indexOf('sb') // 2
arr.indexOf('xx') //-1 //不存在,返回 -1

字符串

是否以指定字符串结尾

1
2
str.endsWith('sss')
//str 是否以 sss 结尾,返回 true 或 false

删除开头和结尾的空格

空格包括所有的空格字符 (space, tab, no-break space 等) 以及所有的行结束符(如 LF,CR)

1
str.trim();

删除所有空格

仅存在空格

1
str.split(" ").join("");

存在了制表符等空白符

1
str.replace(/\s+/g, "");

使 input 失去焦点

密码输入,如果没有失去焦点,获取到的信息可能不正确

1
2
var input = document.getElementById("password");
input.blur();

input radio 点击事件

1
2
3
4
5
6
<label>
<input type="radio" name="myname" id="myname_yes" value="1">
</label>
<label>
<input type="radio" name="myname" id="myname_no" value="0" checked>
</label>
1
2
3
4
5
6
7
// 点击事件change
$('input[type=radio][name=myname]').change(function () {
// 获取input radio选中值,方法一
var myvalue = $('input:radio[name="myname"]:checked').val();
// 获取input radio选中值,方法二
var myvalue = $(this).val();
});

解析 location URL 中参数

1
2
3
4
5
6
7
8
9
10
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}

浏览器全屏和退出全屏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 全屏
*/
let toFullScreen = () => {
let el = document.documentElement;
let rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;

//typeof rfs != "undefined" && rfs
if (rfs) {
rfs.call(el);
} else if (typeof window.ActiveXObject !== "undefined") {
//for IE,这里其实就是模拟了按下键盘的F11,使浏览器全屏
let wscript = new ActiveXObject("WScript.Shell");
if (wscript != null) {
wscript.SendKeys("{F11}");
}
} else {
alert("浏览器不支持全屏");
}
}

/**
* 退出全屏
*/
let exitFullscreen = function () {
let el = parent.document;
let cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen;

//typeof cfs != "undefined" && cfs
if (cfs) {
cfs.call(el);
} else if (typeof window.ActiveXObject !== "undefined") {
//for IE,这里和fullScreen相同,模拟按下F11键退出全屏
let wscript = new ActiveXObject("WScript.Shell");
if (wscript != null) {
wscript.SendKeys("{F11}");
}
} else {
alert("切换失败,可尝试Esc退出")
}
}

当前站点 ip:端口

1
window.location.host

360 浏览器中不支持 replaceAll 问题

使用 replace 解决:

1
2
//content 中 type="date" 全部替换为 type="local_date"
let result = content.replace(/type=\"date\"/g, "type=\"local_date\"")