for (var i=0; i < 10; i++){
doSomething(i);
}
alert(i); //10
if (true) {
var color = "blue";
}
alert(color); //"blue"
function add(num1, num2) {
sum = num1 + num2;
return sum;
}
var result = add(10, 20); //30
alert(sum); //30
(function(){
//这里是块级作用域
})();
function(){ //这段代码会导致语法错误,是因为 JavaScript 将 function 关键字当作一个函数声明的开始,而函数声明后面不能跟圆括号。然而,函数表达式的后面可以跟圆括号。
//这里是块级作用域
}(); //出错!
function outputNumbers(count){
(function () {
for (var i=0; i < count; i++){
alert(i);
}
})();
alert(i); //导致一个错误!
}
function MyObject(){ //构造函数
//私有变量和私有函数(均无法在外部访问)
var privateVariable = 10;
function privateFunction(){
return false;
}
//特权方法作为闭包有权访问私有变量和私有函数
this.publicMethod = function (){
privateVariable++;
return privateFunction();
};
}
用私有和特权成员,可以隐藏那些不应该被直接修改的数据,例如:
function Person(name){
this.getName = function(){
return name;
};
this.setName = function (value) {
name = value;
};
}
var person = new Person("Nicholas");
alert(person.getName()); //"Nicholas"
person.setName("Greg");
alert(person.getName()); //"Greg"
注:构造函数模式的缺点是针对每个实例都会创建同样一组新方法 。
var person = new Object(); // 或 var person = {};
person.name = "Nicholas";
person.age = 29;
var person = {
name : "Nicholas",
age : 29
};
var person = {
"name" : "Nicholas",
"age" : 29,
5 : true
};
alert(person["name"]); //"Nicholas" alert(person.name); //"Nicholas" 推荐
var colors = new Array();
var colors = new Array(20);
var colors = new Array("red", "blue", "green");
var colors = Array(3); //也可省略new,这意味着自定义的构造函数只需像普通函数那样定义,用this指定属性,然后像普通函数那样使用即可创建实例。
var colors = ["red", "blue", "green"]; var names = [];
var colors = ["red", "blue", "green"]; // 创建一个包含 3 个字符串的数组 colors.length = 2; alert(colors[2]); //undefined
var colors = ["red", "blue", "green"]; // 创建一个包含 3 个字符串的数组 colors.length = 4; alert(colors[3]); //undefined
var colors = ["red", "blue", "green"]; // 定义一个字符串数组 alert(colors[0]); // 显示第一项 colors[2] = "black"; // 修改第三项 colors[3] = "brown"; // 新增第四项
方法1:
if (value instanceof Array){
//对数组执行某些操作
}
方法2: 推荐
if (Array.isArray(value)){
//对数组执行某些操作
}
var colors = ["red", "blue", "green"]; // 创建一个包含 3 个字符串的数组
alert(colors.toString()); // red,blue,green 默认返回以逗号拼接的字符串
alert(colors.valueOf()); // red,blue,green 返回的还是数组
alert(colors); // red,blue,green
var person1 = {
toLocaleString : function () { //toLocalString默认与toString输出相同
return "Nikolaos";
},
toString : function() { //重写toString函数
return "Nicholas";
}
};
var person2 = {
toLocaleString : function () {
return "Grigorios";
},
toString : function() {
return "Greg";
}
};
var people = [person1, person2];
alert(people); //Nicholas,Greg
alert(people.toString()); //Nicholas,Greg
alert(people.toLocaleString()); //Nikolaos,Grigorios
也可利用Join手工构建返回的数组字符串:
var colors = ["red", "green", "blue"];
alert(colors.join(",")); //red,green,blue
alert(colors.join("||")); //red||green||blue
注:如果数组中的某一项的值是 null 或者 undefined,那么该值在 join()、toLocaleString()、 toString()和 valueOf()方法返回的结果中以空字符串表示。
var colors = ["red", "blue"];
colors.push("brown"); // 添加另一项
colors[3] = "black"; // 添加一项
alert(colors.length); // 4
var item = colors.pop(); // 取得最后一项
alert(item); //"black"
var colors = new Array(); //创建一个数组
var count = colors.push("red", "green"); //推入两项
alert(count); //2
count = colors.push("black"); //推入另一项
alert(count); //3
var item = colors.shift(); //取得第一项
alert(item); //"red"
alert(colors.length); //2
var colors = new Array(); //创建一个数组
var count = colors.unshift("red", "green"); //推入两项,按顺序在前面插入,即数组顺序为red, green
alert(count); //2
count = colors.unshift("black"); //推入另一项
alert(count); //3
var item = colors.pop(); //取得最后一项
alert(item); //"green"
alert(colors.length); //2
反转数组顺序: var values = [1, 2, 3, 4, 5]; values.reverse(); alert(values); //5,4,3,2,1 sort方法默认按从小到大排序,会调用数组每项的toString方法转成字符串来比较,这会导致在比较数字时出现问题: var values = [0, 1, 5, 10, 15]; values.sort(); alert(values); //0,1,10,15,5
function compare(value1, value2) {
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
或:
function compare(value1, value2){
return value2 - value1;
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
alert(values); //0,1,5,10,15
操作方法:
数组拼接:
var colors = ["red", "green", "blue"];
var colors2 = colors.concat("yellow", ["black", "brown"]);
alert(colors); //red,green,blue 创建新数组,不影响源数组
alert(colors2); //red,green,blue,yellow,black,brown
数组切片: 如果 slice()方法的参数中有一个负数,则用数组长度加上该数来确定相应的位置。
var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
alert(colors2); //green,blue,yellow,purple
alert(colors3); //green,blue,yellow 创建新数组,不影响源数组
功能最强大方法:splice()
splice()的主要用途是向数组的中部插入项,但使用这种方法的方式则有如下 3 种。
? 删除:可以删除任意数量的项,只需指定 2 个参数:要删除的第一项的位置和要删除的项数。
例如,
例如, splice(0,2)会删除数组中的前两项。
? 插入:可以向指定位置插入任意数量的项,只需提供 3 个参数:起始位置、 0(要删除的项数)
和要插入的项。如果要插入多个项,可以再传入第四、第五,以至任意多个项。例如,
splice(2,0,"red","green")会从当前数组的位置 2 开始插入字符串"red"和"green"。
? 替换:可以向指定位置插入任意数量的项,且同时删除任意数量的项,只需指定 3 个参数:起
始位置、要删除的项数和要插入的任意数量的项。插入的项数不必与删除的项数相等。例如,
splice (2,1,"red","green")会删除当前数组位置 2 的项,然后再从位置 2 开始插入字符串
"red"和"green"。
splice()方法始终都会返回一个数组,该数组中包含从原始数组中删除的项(如果没有删除任何
项,则返回一个空数组)。
项,则返回一个空数组)。
位置方法:
ECMAScript 5 为数组实例添加了两个位置方法: indexOf()和 lastIndexOf()。这两个方法都接收
两个参数:要查找的项和(可选的)表示查找起点位置的索引。其中,
两个参数:要查找的项和(可选的)表示查找起点位置的索引。其中, indexOf()方法从数组的开头(位
置置 0)开始向后查找, lastIndexOf()方法则从数组的末尾开始向前查找。
这两个方法都返回要查找的项在数组中的位置,或者在没找到的情况下返回
这两个方法都返回要查找的项在数组中的位置,或者在没找到的情况下返回?1。在比较第一个参数
与数组中的每一项时,会使用全等操作符;也就是说,要求查找的项必须严格相等(就像使用
与数组中的每一项时,会使用全等操作符;也就是说,要求查找的项必须严格相等(就像使用===一样)。
迭代方法:
ECMAScript 5 为数组定义了 5 个迭代方法。每个方法都接收两个参数:要在每一项上运行的函数和
(可选的)运行该函数的作用域对象——影响 this 的值。传入这些方法中的函数会接收三个参数:数
组项的值、该项在数组中的位置和数组对象本身。根据使用的方法不同,这个函数执行后的返回值可能
会也可能不会影响方法的返回值。以下是这 5 个迭代方法的作用。
? every():对数组中的每一项运行给定函数,如果该函数对每一项都返回 true,则返回 true。(与运算)
? filter():对数组中的每一项运行给定函数,返回该函数会返回 true 的项组成的数组。(条件过滤)
? forEach():对数组中的每一项运行给定函数。这个方法没有返回值。(对每项执行相同操作,无返回值)
? map():对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。(对每项执行相同操作,有返回值)
? some():对数组中的每一项运行给定函数,如果该函数对任一项返回 true,则返回 true。(或运算)
以上方法都不会修改数组中的包含的值。
var numbers = [1,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item, index, array){
return (item > 2);
});
alert(everyResult); //false
var someResult = numbers.some(function(item, index, array){
return (item > 2);
});
alert(someResult); //true
var mapResult = numbers.map(function(item, index, array){
return item * 2;
});
alert(mapResult); //[2,4,6,8,10,8,6,4,2]
numbers.forEach(function(item, index, array){
//执行某些操作
});
归并方法:使用 reduce()还是 reduceRight(),主要取决于要从哪头开始遍历数组。除此之外,它们完全相同。
使用 reduce()方法可以执行求数组中所有值之和的操作,比如:
var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
return prev + cur;
});
alert(sum); //15
function sum (num1, num2) {
return num1 + num2;
}
====> 等价于(除了什么时候可以通过变量访问函数这一点区别之外,函数声明与函数表达式的语法其实是等价的。 函数声明有提升,当变量初始化无提升)
var sum = function(num1, num2){
return num1 + num2;
};
每个函数都是 Function 类型的实例,而且都与其他引用类型一样具有属性和方法。由于函数是对象,因此函数名实际上也是一个指向函数对象的指针,不会与某个函数绑定。
一个函数可以有多个名字。
function sum(num1, num2){
return num1 + num2;
}
alert(sum(10,10)); //20
var anotherSum = sum;
alert(anotherSum(10,10)); //20
sum = null;
alert(anotherSum(10,10)); //20
函数内部属性this:
在函数内部,有两个特殊的对象: arguments 和 this。 arguments主要是保存函数参数的作用。
this引用的是函数据以执行的环境对象——或者也可以说是 this 值(当在网页的全局作用域中调用函数时,this 对象引用的就是 window)。
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
sayColor(); //"red"
o.sayColor = sayColor;
o.sayColor(); //"blue"
上面这个函数 sayColor()是在全局作用域中定义的,它引用了 this 对象。由于在调用函数之前,
this 的值并不确定,因此 this 可能会在代码执行过程中引用不同的对象。当在全局作用域中调用
sayColor()时, this 引用的是全局对象 window;换句话说,对 this.color 求值会转换成对
window.color 求值,于是结果就返回了"red"。而当把这个函数赋给对象 o 并调用 o.sayColor()
时, this 引用的是对象 o, 因此对 this.color 求值会转换成对 o.color 求值,结果就返回了"blue"。
注:函数的名字仅仅是一个包含指针的变量而已。因此,即使是在不同的环境中执行,全局的 sayColor()函数与 o.sayColor()指向的仍然是同一个函数。
在全局函数中, this 等于 window,而当函数被作为某个对象的方法调用时, this 等于那个对象。不过,匿名函数的执行环境具有全局性,因此其 this 对象通常指向 window。
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //"The Window"(在非严格模式下)
函数内部属性func.inner:
这个属性中保存着调用当前函数的函数的引用,如果是在全局作用域中调用当前函数,它的值为 null。
length 属性:表示函数希望接收的命名参数的个数
function sayName(name){
alert(name);
}
function sum(num1, num2){
return num1 + num2;
}
function sayHi(){
alert("hi");
}
alert(sayName.length); //1
alert(sum.length); //2
alert(sayHi.length); //0
apply()和call()方法:
每个函数都包含两个非继承而来的方法: apply()和 call()。这两个方法的用途都是在特定的作
用域中调用函数,实际上等于设置函数体内 this 对象的值。首先, apply()方法接收两个参数:一个
是在其中运行函数的作用域,另一个是参数数组。其中,第二个参数可以是 Array 的实例,也可以是
arguments 对象。
function sum(num1, num2){
return num1 + num2;
}
function callSum1(num1, num2){
return sum.apply(this, arguments); // 传入 arguments 对象
}
function callSum2(num1, num2){
return sum.apply(this, [num1, num2]); // 传入数组
}
alert(callSum1(10,10)); //20
alert(callSum2(10,10)); //20
call()方法与 apply()方法的作用相同,它们的区别仅在于接收参数的方式不同。对于 call()方法而言,第一个参数是 this 值没有变化,变化的是其余参数都直接传递给函数。换句话说,在使用
call()方法时,传递给函数的参数必须逐个列举出来。在使用 call()方法的情况下, callSum()必须明确地传入每一个参数。结果与使用 apply()没有什么不同。至于是使用 apply()还是 call(),完全取决于你采取哪种给函数传递参数的方式最方便。如果你打算直接传入 arguments 对象,或者包含函数中先接收到的也是一个数组,那么使用 apply()肯定更方便;否则,选择 call()可能更合适。(在不给函数传递参数的情况下,使用哪个方法都无所谓。)
事实上,传递参数并非 apply()和 call()真正的用武之地;它们真正强大的地方是能够扩充函数赖以运行的作用域。
使用 call()(或 apply())来扩充作用域的最大好处,就是对象不需要与方法有任何耦合关系。
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
sayColor(); //red
sayColor.call(this); //red
sayColor.call(window); //red
sayColor.call(o); //blue
bind()方法:这个方法会创建一个函数的实例,其 this 值会被绑定到传给 bind()函数的值。例如:
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o); //将sayColor的函数别名绑定到o作用域对象.
objectSayColor(); //blue
var uri = "http://www.wrox.com/illegal value.htm#start"; //"http://www.wrox.com/illegal%20value.htm#start" alert(encodeURI(uri)); //"http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start" alert(encodeURIComponent(uri));
var uri = "http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start"; //http%3A%2F%2Fwww.wrox.com%2Fillegal value.htm%23start alert(decodeURI(uri)); //http://www.wrox.com/illegal value.htm#start alert(decodeURIComponent(uri));
var color = "red";
function sayColor(){
alert(window.color);
}
window.sayColor(); //"red"
var === null
typeof(exp) == "undefined"
var str = ‘ hello workd haha‘; var res = str.replace(/\s+/g, ‘‘)
var aa = {‘a‘: 1, ‘b‘: 2}
console.log(Object.getOwnPropertyNames(aa).length) 或 Object.keys(aa).length
var entityGroupEle = entityRectEle.parentNode;
var badEntityPaths = entityGroupEle.getElementsByTagName(‘path‘);
while (badEntityPaths.length > 0) {
entityGroupEle.removeChild(badEntityPaths[0]);
badEntityPaths = entityGroupEle.getElementsByTagName(‘path‘);
}
//添加文档加载完要执行的函数
function addLoadEvent(func){
var oldonload = window.onload;
if(typeof window.onload != ‘function‘){
window.onload = func;
} else {
window.onload = function(){
oldonload();
func();
}
}
}
//在某个dom元素后插入新元素
function insertAfter(newElement, targetElement){
var parent = targetElement.parentNode;
if(parent.lastChild == targetElement){
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
//为某个dom元素添加css类
function addClass(element, value){
if(!element.className){ //若未定义class属性
element.className = value;
} else{ //在已有css上添加新样式
newClassName = element.className;
newClassName += " ";
newClassName += value;
element.className = newClassName;
}
}
将dom元素A插入到父元素为B的dom元素C前面: B.insertBefore(A, C); //A为新插入元素,C为参照元素, B为新插入元素的父元素. 当C为null时,表示将A插入到B的最后.
element.getElementsByTagName("tagName")
方法1:
window.addEventListener(‘resize‘, resizeRender, false);
window.removeEventListener(‘resize‘, resizeRender, false);
方法2:
window.onresize = resize;
window.onresize = null;
方法3:
$(window).on(‘resize‘, resize);
$(window).unbind(‘resize‘, resize);
方法4:
$(window).resize(function () {});
var pagex = event.pageX || scroll().left + event.clientX; var pagey = event.pageY || scroll().top + event.clientY;
var onMouseMove = function(evt){
var svgDivBox = $(‘.unlabel-text-svg-box‘)[0];
var dy = evt.pageY - $(svgDivBox).offset().top;
var dyPercentage = dy / svgDivBox.clientHeight;
// svgDivBox.scrollTop = dyPercentage * svgDivBox.scrollHeight //与下者等价
svgDivBox.scrollTo(0, dyPercentage * svgDivBox.scrollHeight);
}
window.innerWidth(document.body.clientWidth还是包含)
document.oncontextmenu = function(){return false;} //整个页面的默认右击事件均失效
$(document).bind("contextmenu",function(e){
return false;
});
推荐:
document.getElementsByClassName(‘ti-modal ti-fade ti-in‘)[0].oncontextmenu = function (e) {
e.preventDefault();
};
原文:https://www.cnblogs.com/luckyboylch/p/12330216.html