lovecn / lovecn.github.io

个人记录
5 stars 5 forks source link

javascript笔记 #14

Open lovecn opened 9 years ago

lovecn commented 9 years ago
1.变量提升
var foo='hello';

(function(){
var foo=foo||'world' ;
console.log(foo);//输出world

})();

如同:
var foo='hello';
(function(){
var foo;
foo=foo||'world' ;
console.log(foo);
})();
2.找出对象 arguments 当中数字第二大的值
function getSecondMax(){
return Array.prototype.slice.call(arguments,0).sort(function(a,b){return (a>b?-1:1)}) [1] ;
}
console.log(getSecondMax(12,3,43,4,5,7,87));
3.参数是否可以引用传递

function test(user) {  user['age'] = '24';}
var my = {  name : 'Zjmainstay'}
test(my);
console.log(my);{name: “Zjmainstay”, age: “24″}
function test(user) {  user = {  name : 'sijiaomao'};}
var my = {  name : 'Zjmainstay'}
test(my);
console.log(my); {  name : ‘sijiaomao’} 
4.闭包

for(var i = 0;i < 5;i++) {
    setTimeout(function(){
        alert(i);
    },500);
}

应该用
for(var i=0; i<5; i++) {
(function(index){
setTimeout(function(){
alert(index);
},500);
})(i);
}

在数据库系统MySQL中 有多种字符集,其中utf8_unicode_ci和utf8_general_ci是最常用的,但是utf8_general_ci对某些语言的支持有一些小问题,如果可以接受,那最好使用utf8_general_ci,因为它速度快。否则,请使用较为精确的utf8_unicode_ci,不过速度 会慢一些。

隐藏这个ajax请求
注意不要直接用jQuery的jsonp实现,因为你的接口本来是ajax方式实现的,那么说明肯定是同源的请求,如果直接改成jQuery的jsonp,实质上还是通过xhr发出的,jQuery对同源jsonp做了特殊处理,并不是按照动态添加script标签的方式进行的
nginx allow deny是有顺序的,如果你

allow 192.168.1.0/24
# ...
deny 192.168.1.5
192.168.1.5是可以访问的
下雪的效果是把https://github.com/loktar00/JQuery-Snowfall修改了一下,不再使用图片。
如果需要,在你的页面的body最后添加下面的代码,就可以飘飘飘了。
<script src="http://static.segmentfault.com/build/3rd/snowfall.min.js"></script>
//第一个参数是你想要插入的节点,第二个参数则是目标元素了。
function insertAfter(newElement,targetElement) { 
  var parent = targetElement.parentNode; 
  if (parent.lastChild == targetElement) { 
    parent.appendChild(newElement); 
  } else { 
    parent.insertBefore(newElement,targetElement.nextSibling); 
  } 
}

function addClass(element,value) { 
  if (!element.className) { 
    element.className = value; 
  } else { 
    newClassName = element.className; 
    newClassName+= " "; 
    newClassName+= value; 
    element.className = newClassName; 
  } 
} 
//Placeholder
function resetFields(whichform) { 
  if (Modernizr.input.placeholder) return; 
  for (var i=0; i<whichform.elements.length; i++) { 
    var element = whichform.elements[i]; 
    if (element.type == "submit") continue; 
    var check = element.placeholder || element.getAttribute('placeholder'); 
    if (!check) continue; 
    element.onfocus = function() { 
      var text = this.placeholder || this.getAttribute('placeholder'); 
      if (this.value == text) {  
        this.className = ''; 
        this.value = ""; 
      } 
    } 
    element.onblur = function() { 
      if (this.value == "") { 
        this.className = 'placeholder'; 
        this.value = this.placeholder || this.getAttribute('placeholder'); 
      } 
    } 
    element.onblur(); 
  } 
}

var clear = function (ary) {
    console.log(ary); //输出:[1,2,3]     
    ary = [];
    console.log(ary); //输出:[]  
    console.log(a); //输出:[1,2,3]  
};
var a = [1, 2, 3];
clear(a);
console.log(a); //输出:[1,2,3]  

Object.prototype.del=function(v){
    var i;
    for(i in this){
        if(this[i]===v)
            this.splice(i,1);
    }
};

var exam = {"0": {
            "exam_grade_id": "1",
            "exam_name": "普通话考试",
            "grades": {
                "姓名": "你娃",
                "总分": "60",
            }
        },
"1": {
            "exam_grade_id": "2",
            "exam_name": "四六级考试",
            "grades": {
                "姓名": "我娃",
                "总分": "550",
            }
        }
}
exam2 = Object.keys(exam).map(function(k){return exam[k]});

var grid = [[-1, -1, 2, -1], [-1, 4, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]];
var top0 = top1 = top2 = top3 = [];
for (x = 0; x < 4; x++) {
    for (y = 0; y < 4; y++) {
        if (grid[y][x] != -1) {
            eval('top' + x).push(grid[y][x]);
        }
    }
}
console.log(top0);
console.log(top1);
console.log(top2);
console.log(top3);
[4, 2]
[4, 2]
[4, 2]
[4, 2]
//这里犯了一个很低级的Bug,像第二行这样初始化变量,变成了引用类型,只要top0到top3中的任何变量发生了变化,其他全部都会发生变化。
修改成如下就正常了

var grid = [[-1, -1, 2, -1], [-1, 4, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]];
var top0 = [];
var top1 = [];
var top2 = [];
var top3 = [];
for (x = 0; x < 4; x++) {
    for (y = 0; y < 4; y++) {
        if (grid[y][x] != -1) {
            eval('top' + x).push(grid[y][x]);
        }
    }
}
console.log(top0);
console.log(top1);
console.log(top2);
console.log(top3);

将阿拉伯数字每隔三位为一逗号分离 
(?=)为js正则表达式中的正向前瞻,出现在特定字符之前的字符,只有当字符后面跟着某个特定字符才去捕获它。

你的例子中,/(\d{3})(?=[^$])/g表示只有在匹配了(\d{3})之后匹配到了[^$]才算匹配成功,$为字符串的结束符,[^$]表示除字符串结束符以外的字符。如果去掉这部分,那么可能在数字最后也会添加上,
123456789.replace(/(\d{3})/g, "$1,"); // 123,456,789,
123456789.replace(/(\d{3})(?=[^$])/g, "$1,"); // 123,456,789

var a = 1;
delete a;//false
 a = 1;
 delete a;//true
对象的属性有4个特性(attributes),其中一个叫configurable,如果这个属性值为false则一定不能被delete。

var x = 1;
Object.getOwnPropertyDescriptor(this,'x');
//结果是Object {value: 1, writable: true, enumerable: true, configurable: false}
configurable为false,所以不能删除。

123.toString()
会直接报错

var a = 123; a.toString();
这个就是正确的。
JavaScript采用 IEEE 754 的规范 双精度数字。就是都是小数
JavaScript 中只有一种数字类型:基于 IEEE 754 标准的双精度 。它并没有为整数给出一种特定的类型。所以所有的数字都是小数
123.toString() 等价于 123.0toString()
除非使用 (123).toString()
(123).toString() 等价于 123.0.toString() 和 123..toString()
因为 123. === 123.0 true
js语法的二义性造成的,.这个符号具有二义性,而计算机中的逻辑是不能有二义性的,所以报错了

+8615145698763
+86 151-4569-8763
使用 javascript 统一将上述不同格式数据整理为标准11位数字手机号
str.replace(/[+-\s]/g, '').slice(-11);
str.replace(/[-+ ]/g, '').replace(/^86(\d{11})/gm, '$1');

在forEach执行callback时的this值,比如:
 var array = [1,2,3];
 var result = [];
 array.forEach(function(i){
     this.push(i*i);
 },result);  // result ==> [1, 4, 9]

 或者在reduce里,

 [1,2,3].reduce(
     function(p,v){
         return p + v
     })   // 6

 [1,2,3].reduce(
     function(p,v){
         return p + v
     },10)   // 16

match匹配成功时会返回数组:

如果正则为全局匹配,那么数组的第一个及以后元素存放的都是匹配的字符串,不再存放匹配的分组
如果正则不为全局匹配,那么数组的第一个元素存放的是匹配的字符串,第二个及以后元素存放的是匹配的分组
换行写字符串
var s = "div{\
            backgroud:red\
        }";
match匹配成功时会返回数组:

如果正则为全局匹配,那么数组的第一个及以后元素存放的都是匹配的字符串,不再存放匹配的分组
如果正则不为全局匹配,那么数组的第一个元素存放的是匹配的字符串,第二个及以后元素存放的是匹配的分组
var a = 'h&nbsp;hello&lt;world&gt;!!!&lt;script&gt;alert(1)&lt;/script&gt;'
    alert(a);
    var c = document.createElement('div');
    c.innerHTML = a;
    a = c.innerText || c.textContent;
    c = null;
    alert(a);

var fullname = 'John Doe';

var obj = {

fullname: 'Colin Ihrig',

prop: {

fullname: 'Aurelio De Rosa',

getFullname: function() {

return this.fullname;

}}}; 
var test = obj.prop.getFullname;

console.log(test());

var str = 'dog,[cat,lion],[bird,chicken,duck]';
JSON.parse('['+str.replace(/\w+/g, function(a){return '"'+a+'"'})+']')// [dog,[cat,lion],[bird,chicken,duck]];

var menu =document.getElementById("main-menu").childNodes;
for(var i=0;i<menu.length;i++){
  (function(arg){
        menu[i].onclick=function(arg){
             //
        }
    })(i)
}
try {
    window.localStorage.foobar = "foobar";
} catch(_) {
    alert("本地储存写入错误,若为safari浏览器请关闭隐身模式浏览。");
}

^(ab|a)$ 匹配ab 或 a

^[ab|a]$ 匹配  a或b或|
[]和()是不一样的,在[]里面元字符将失去原本特殊的含义,变成只是字符本身,所以[a|b]是可以匹配里面三个字符中的任意一个,而(a|b)是匹配a或者b并作为一个分组

 XMLHttpRequest Script Injection
function xhrLoadJS (url, callback){
  var xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
      if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
        var script = document.createElement('script');
        script.type = 'text/script';
        script.text = xhr.responseText;
        eval(xhr.responseText);  // 执行代码
        document.body.appendChild(script);
        callback();
      }
    }
  }
  xhr.send(null);
}
function bindClick(){
    var li = document.getElementsByTagName('li');
    for(var i=0; i<li.length; i++){
        li[i].onClick = (function(j){
            console.log('click the '+j+' li tag');
        })(i);
    }
}
javascript并没有提供类这样的机制,但是我们可以通过闭包来模拟出类的机制,不同的对象实例拥有独立的成员和状态。 用闭包实现的简单的类,里面的name属性是私有的,外部无法进行访问,只能通过setName和getName进行访问。
function Student(){
    var name = 'wenzi';

    return {
        setName : function(na){
            name = na;
        },

        getName : function(){
            return name;
        }
    }
}
var stu = new Student();
console.log(stu.name); // undefined
console.log(stu.getName()); // wenzi

function jsonClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}
var clone = jsonClone({ a:1 });

var a = { foo: 'bar' }
var b = [a, 2]

console.log(b.indexOf(1))
// <- -1

console.log(b.indexOf({ foo: 'bar' }))
// <- -1

console.log(b.indexOf(a))
// <- 0

console.log(b.indexOf(a, 1))
// <- -1

b.indexOf(2, 1)
// <- 1
var a = [1, 2, 5]

1 in a
// <- true, but because of the 2!

5 in a
// <- false
问题是in操作符是检索对象的键而非值

Array.prototype.sum = function () {
    return this.reduce(function (partial, value) {
        return partial + value
    }, 0)
};

[3,4,5,6,10].sum()
// <- 28

.filter只返回在回调函数中返回true值的元素
[void 0, null, false, '', 1].filter(function (value) {
    return value
})
// <- [1]
max = -Infinity
satisfied = [10, 12, 10, 8, 5, 23].some(function (value, index, array) {
    if (value > max) max = value
    return value < 10
})

console.log(max)
// <- 12

satisfied
// <- true
['_', 't', 'a', 'n', 'i', 'f', ']'].forEach(function (value, index, array) {
    this.push(String.fromCharCode(value.charCodeAt() + index + 2))
}, out = [])

out.join('')
// <- 'awesome'

['_', 't', 'a', 'n', 'i', 'f', ']'].forEach(function (value, index, array) {
    this.push(String.fromCharCode(value.charCodeAt() + index + 2))
}, out = [])

out.join('')
// <- 'awesome'

function concat (input) {
    return input.reduce(function (partial, value) {
        if (partial) {
            partial += ', '
        }
        return partial + value
    }, '')
}

concat([
    { name: 'George' },
    { name: 'Sam' },
    { name: 'Pear' }
])
// <- 'George, Sam, Pear'

var a = [
    "3040131111",
    "小明",
    "1",
    "大学体育Ⅰ",
    "通识课",
    "2.00",
    "75",
    "总评成绩",
    "2.50",
    "A16603001A",
    "32.00",
    "3040133109",
    "小明",
    "1",
    "基础英语Ⅰ",
    "通识课",
    "4.00",
    "80",
    "总评成绩",
    "3.00",
    "A17001021A",
    "64.00"
], b = [], i = 0;

while(true){
    var c = a.slice(i, i += 11);//从数组中取11个元素出来
    if(c.length !== 11){//如果没取成功,当元素个数不符合要求时,退出
        break;
    }
    b.push({//添加至新数据中
        "学号": c[0],
        "姓名": c[1],
        "学期": c[2],
        "课程": c[3],
        "类别": c[4],
        "学分": c[5],
        "成绩": c[6],
        "成绩类型":c[7],
        "绩点": c[8],
        "课程彪悍": c[9],
        "课时": c[10]
    });
};
console.log(JSON.stringify(b));
JavaScript可以执行函数表达式,但是不能执行函数声明,也就是说,JavaScript把

function(){ 
    alert(3);
}
当做了函数声明,想要正常运行,在函数声明的外部套一对小括号即可,像这样:

(function(){ 
    alert(3);
})();

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
    function(data){
    $.each(data.items, function(i,item){
        $("<img/>").attr("src", item.media.m).appendTo("#images");
        if ( i == 3 ) return false;
    });
});
$.fn.extend({
    demo: function () {
        alert('demo');
    }
});

$('#target').demo();

$.extend({
    test: function () {
        alert('test')
    }
});
$.test();

var A = 1;

(function A() {
    A = 2;
    console.log(typeof A);
    delete A;
    console.log(typeof A);
})();
这是个立即执行的函数表达式(IIFE),但是同时也是个具名函数表达式(NFE)。

有两个特性:

- 函数名的标识符(A)只能从内部访问。
- 函数名的标识符(A)不可以再绑定其他值,即不可更改。
所以:

A = 2      //  无效
delelte A  //  无效

// 确定是有数字组成的字符串
'123' * 1;
'123' / 1;
'123' - 0;
'123' | 0;
+'123';
~~'123';
Number('123');
parseInt('123', 10);
![Uploading image.png…]()
调用手机摄像头拍照,然后上传照片 <input type="file" accept="image/*" /> 

String.prototype.trim = function (char, type) {
    if (char) {
        if (type == 'left') {
            return this.replace(new RegExp('^\\'+char+'+', 'g'), '');
        } else if (type == 'right') {
            return this.replace(new RegExp('\\'+char+'+$', 'g'), '');
        }
        return this.replace(new RegExp('^\\'+char+'+|\\'+char+'+$', 'g'), '');
    }
    return this.replace(/^\s+|\s+$/g, '');
};

// 去除字符串首尾的全部空白
var str = ' Ruchee ';
console.log('xxx' + str.trim() + 'xxx');  // xxxRucheexxx

// 去除字符串左侧空白
str = ' Ruchee ';
console.log('xxx' + str.trim(' ', 'left') + 'xxx');  // xxxRuchee xxx

// 去除字符串右侧空白
str = ' Ruchee ';
console.log('xxx' + str.trim(' ', 'right') + 'xxx');  // xxx Rucheexxx

// 去除字符串两侧指定字符
str = '/Ruchee/';
console.log(str.trim('/'));  // Ruchee

// 去除字符串左侧指定字符
str = '/Ruchee/';
console.log(str.trim('/', 'left'));  // Ruchee/

// 去除字符串右侧指定字符
str = '/Ruchee/';
console.log(str.trim('/', 'right'));  // /Ruchee
XMLHttpRequest Level 2 FormData 提交二进制文件
var oOutput = document.getElementById("output");
    var oData = new FormData(document.forms.namedItem("fileinfo")); 

    oData.append("CustomField", "This is some extra data"); 
    var oReq = new XMLHttpRequest();
    oReq.open("POST", "stash.php", true); 

    oReq.onload = function(oEvent) { 
        if (oReq.status == 200) { 
            oOutput.innerHTML = "Uploaded!"; 
        } 
        else { 
            oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>"; 
        } 
    }; 
    oReq.send(oData); 
}
使用jQuery来发送FormData,但必须要正确的设置相关选项:

<a id="sendForm" href="javascript:;">Stash the file!</a>

$("#sendForm").click(function(){
    var fd = new FormData(document.forms.namedItem("fileinfo")); 
    var request = $.ajax({ 
        url: "test.json", 
        type: "POST", 
        data: fd, 
        processData: false,  // 告诉jQuery不要去处理发送的数据   contentType: false   // 告诉jQuery不要去设置Content-Type请求头 
    });

    request.done(function(json){
        console.log("a");
    });

    request.fail(function(){
        console.log("b");
    });

});

这段在定义匿名函数的同时立刻调用了,而这个调用是在循环体内的,所以3次调用的i是0、1、2,所以绑定的3个onclick也是0、1、2
window.onload=function(){
    var aBtn = document.getElementsByTagName('input');
    for(var i=0;i<aBtn.length;i++){
        (function(index){
            aBtn[index].onclick=function(){
                alert(index);
            };
        })(i);
    }
};
而不是这样写

window.onload=function(){
    var aBtn = document.getElementsByTagName('input');
    for(var i=0;i<aBtn.length;i++){
        aBtn[index].onclick=function(){
                alert(index);
            };
    }
};

var isIE = function(ver){
    var b = document.createElement('b')
    b.innerHTML = '<!--[if IE ' + ver + ']><i></i><![endif]-->'
    return b.getElementsByTagName('i').length === 1
}
if(isIE(6)){
    // IE 6
}
// ...
if(isIE(9)){
    // IE 9
}

创建数据的三种方法。
new Array();
new Array(size);
new Array(element0, element1, ..., elementn);
当传入一个参数时,是第二种构建方法。
以i=2来说。
temp = Array(2+1).join(2);
创建长度为为3的数据,
join(2),2为分隔符。 所以输出 22;
Array(i + 1) 表示长度为i+1的数组,但是均为空,join方法的参数代表分隔符,这里代表以2,4,6,为分隔符,所以为空2空2空,空4空4空4空4空

写cookie
var a=["1:苹果:3:1:3","1:梨:3:1:3","1:香蕉:2:1:2"];
document.cookie='fruit='+escape(a.join(','))+';expires=Mon, 23 Nov 2015 01:22:04 GMT';
读
var b=document.cookie.match(/(^| )fruit=([^;]*)(;|$)/);
b=b==null?null:unescape(b[2]).split(',');
当一个文本框的内容长度到了10个字符的时候,自动切换到下一个文本框
错误:
var form=document.getElementById('a');
for (var i = 0; i < form.elements.length; i++) {
        form.elements[i].onkeyup=function () {
            if(form.elements[i].value.length==10&&form.elements[i+1]){
                form.elements[i+1].focus();
            }
        }
    }
正确:
var form = document.getElementById('a');

for (var i = 0; i < form.elements.length; i++) {
    (function(m) {
        form.elements[m].onkeyup = function () {
            if(form.elements[m].value.length == 10 && form.elements[m + 1]){
                form.elements[m + 1].focus();
            }
        }
    })(i)
} 
var form = document.getElementById('a');

for (var i = 0; i < form.elements.length; i++) {
    form.elements[i].onkeyup = (function (i) {
        return function() {
            if(form.elements[i].value.length == 10 && form.elements[i + 1]){
                form.elements[i + 1].focus();
            }
        };
    })(i);
}

数组合并
var a = new Array(1,2,3);
var b = new Array('a','b','c');
var c = a.reduce(function(a1,b2){
console.log(typeof(a1));object*3
a1.push(b2);
return a1
}
,b);
console.log(c);["a", "b", "c", 1, 2, 3]
var a = new Array(1,2,3);
var b = new Array(3,4)
a.reduce(function(a1,a2){console.log(typeof(a1));return a1+a2},b);
输出:
object
string
object 的时候都带有第二参数b 么...那个是第一次的a1,然后再对后面进行reduce,第二次reduce的a1则是上一次的返回值,第一个是返回a1这个Array,第三个是返回的a1+a2这个String

<script>alert(a)</script> // 报错:a is not defined
<script>var a=12;alert(a)</script>//但报错后没有停止执行,弹了12
如果换一下位置
<script>var a=12;alert(a)</script>
<script>alert(a)</script> //代码正常

JavaScript解释器在执行脚本时,是按块来执行的。通俗地说,就是浏览器在解析HTML文档流时,如果遇到一个<script>标签,则JavaScript解释器会等到这个代码块都加载完后,先对代码块进行预编译,然后再执行。执行完毕后,浏览器会继续解析下面的HTML文档流,同时JavaScript解释器也准备好处理下一个代码块。

由于JavaScript是按块执行的,所以如果在一个JavaScript块中调用后面块中声明的变量或函数就会提示语法错误。第一端代码就是这情况。

虽然说,JavaScript是按块执行的,但是不同块都属于同一个全局作用域,也就是说,块之间的变量和函数是可以共享的。 这也是第二段代码为什么可以访问前一个块里的a的原因。一个script中报错只会阻止这个script中的代码,而不会影响下面的script标签运行

checkInDate 和checkOutDate 都是localStorage对象上用户自定义的属性。这些属性虽然可以被赋值为一个对象,但是实际存储都是字符串,会调用对象的适当方法(toString或者valueOf)进行转换。

 var a = {};  
 window.localStorage.checkInDate = a;   
 window.localStorage.checkOutDate = null;                   
 console.log(window.localStorage.checkInDate);  // "[Ojbect Ojbect]"
 console.log(window.localStorage.checkOutDate); // "null"   
 console.log(typeof (window.localStorage.checkInDate));  // string
 console.log(typeof (window.localStorage.checkOutDate)); // string

所以这句 if(window.localStorage.checkOutDate==null) 等价于 if ("null" == null) .
查看为一个元素绑定的事件
chrome自带,Event Listeners, 选择 Select Node Only
chrome控制台输入 getEventListeners(node)

在【source】面板中勾选 click事件(以click为例)。 然后操作在页面中触发click事件。
然后 断点会进入到jquery的某一个方法中, 按F11逐行调试, 直到进入你写的业务代码

Chrome 下在Elements选中你要查看的DOM节点后,在控制台输入:

$._data($0).handle      //这种方式依赖于jQuery
$._data($('#element').get(0));
chrome有个插件Visual Event https://chrome.google.com/webstore/detail/visual-event/pbmmieigblcbldgdokdjpioljjninaim?utm_source=chrome-ntp-icon

输入123456789
他会自动处理成12,345,678,9
而不是输入完后在变成12,345,678,9
function formatCurrency(num) {
                num = num.toString().replace(/\$|\,/g, '');
                if (isNaN(num))
                    num = "0";
                sign = (num == ( num = Math.abs(num)));
                num = Math.floor(num * 100 + 0.50000000001);
                cents = num % 100;
                num = Math.floor(num / 100).toString();
                if (cents < 10)
                    cents = "0" + cents;
                for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
                    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
                return (((sign) ? '' : '-') + num + '.' + cents);
            }
            var s=document.getElementById("textbox");
//on('propertychange input')  onpropertychange,就是property(属性)change(改变)的时候,触发事件。这是IE专有的!如果想兼容其它浏览器,有个类似的事件,oninput
            s.onchange=function(){
                this.value=formatCurrency(this.value);
            }
//s = str.replace(/&/g, "&amp;");
function encode(str){
 return $('<div>').text(str).html();
}

function decode(str){
 return $('<div>').html(str).text();
}
a=encode('&')//"&amp;"
decode(a)//"&"

!function a(){ console.log('1'); }()才会执行console.log('1')
作为函数名的标识符(在这里是 a )只能从函数体内部访问,在函数外部访问不到 (IE9+)。
试试!function a(){ console.log(a); }() 是什么结果呢?true
var a = function (){ console.log('1'); }();
=右边是一个立即执行的函数表达式,会把执行结果赋值给a,注意a不是一个函数,而你右边的函数没有返回值,所以执行a是undefined,如果想让a是一个函数的话,要这样写

var a = function (){ console.log('1'); };
var a = function b() {}
// typeof a === "function"
// typeof b === "undefined"
// a.name === "b"  注意:IE下可能 a.name === undefined
如何快速地把正数转换成1,负数转换成-1
function f1(n) {
    return n === 0 ? 0 : n > 0 ? 1 : -1;
}
function f2(n) {
    return n === 0 ? 0 : n / Math.abs(n);
}
function f3(n) {
    return n === 0 ? 0 : ~~n.toString().replace(/(-?).*/, "$11")
}
function f2_ex(n) {
    return n / Math.abs(n) || 0
}
var fakeArray01 = {0:'a',1:'b',length:2};//这是一个标准的伪数组对象 
var arr01 = Array.prototype.slice.call(fakeArray01); 
alert(arr01[0]);//a 
var arr02 = [].slice.call(fakeArray01); 
alert(arr02[0]);//a

符合类数组对象的两条规则

它们都有一个合法的 length 属性(0 到 2**32 - 1 之间的正整数)。
length 属性的值大于它们的最大索引(index)。

改变执行上下文,相应的还有apply,bind

一个obj对象,有log方法和foo属性

var obj = {
log: function() {
console.log(this.foo);
},
foo: 'foo'
};

//可以直接打印obj的foo
console.log(obj.foo);
//或者调用obj的log方法打印
obj.log();

现在有了一个temp对象,也有foo属性
var temp = {
foo:'bar'
};

通过bind,apply,call,使用obj的log方法打印temp对象里的属性,切换上下文。
obj.log.bind(temp)();
obj.log.apply(temp);
obj.log.call(temp);

var students = new Array() ; 
students[0] = "onepiece"; 
students[1] = "naruto"; 
students[2] = "bleach"; 
var json = JSON.stringify(students,switchUpper); 
function switchUpper(key, value) { 
    return value.toString().toUpperCase(); 
} 
json//"ONEPIECE,NARUTO,BLEACH"
/*下面这种方式也可以
var json = JSON.stringify(students, function (key,value) { return value.toString().toUpperCase()}); 
*/

var stuObj = new Object(); 
stuObj.id = "20122014001"; 
stuObj.name = "Tomy"; 
stuObj.age = 25; 

var stuArr = new Array(); 
stuArr[0] = "id"; 
stuArr[1] = "age"; 
stuArr[2] = "addr";//这个stuObj对象里不存在。 

var json = JSON.stringify(stuObj,stuArr); 
//var json = JSON.stringify(stuObj,stuArr,1000); //格式化
//var json = JSON.stringify(stuObj,stuArr,'\t'); 
//var json = JSON.stringify(stuObj,stuArr,'OK '); 

第二个参数存在,并且第二个参数不是function,而是数组的时候 ,第二个参数被忽略了,只是第一个参数被系列化了。

如果原始对象中,有一个成员的值是undefined、函数或XML对象,这个成员会被省略。如果数组的成员是undefined、函数或XML对象,则这些值被转成null。
lovecn commented 9 years ago

http://touchpunch.furf.com/

lovecn commented 9 years ago

http://rehorn.github.io/livepool/

lovecn commented 9 years ago

http://f2e-server.com/

lovecn commented 9 years ago

http://crossorigin.me

lovecn commented 9 years ago

正则可视化http://regexper.com/?#%2F%5E15%7C1%24%2F

lovecn commented 9 years ago

https://www.browserstack.com/ https://www.modern.ie/zh-cn 浏览器兼容测试

lovecn commented 9 years ago

http://html5demos.com/

lovecn commented 9 years ago

http://handlebarsjs.com/ 模板引擎

lovecn commented 9 years ago

奇葩字符 http://www.cnblogs.com/52cik/p/unicode-mark-nonspacing.html

lovecn commented 9 years ago

多浏览器测试工具 http://www.browsersync.io/ html npm install -g browser-sync 静态页面: $ browser-sync start --server --files "css/.css" 用php等语言渲染的动态页面,需要用代理模式 $ browser-sync start --proxy "myproject.dev" --files "css/.css"

lovecn commented 9 years ago

时间处理 https://github.com/moment/moment

lovecn commented 9 years ago

Validform常用功能示例 http://validform.rjboy.cn/demo.html

lovecn commented 9 years ago

https://github.com/leanote/leanote-ios react native app

lovecn commented 9 years ago

http://cdn.peerjs.com/demo/videochat/ WebRTC库简单的视频聊天示例

lovecn commented 9 years ago

http://jointjs.com/demos/javascript-ast 抽象语法树

lovecn commented 9 years ago

Cross-Domain AJAX for IE8 and IE9 https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest

lovecn commented 9 years ago

加解密通关Nazo http://www.cnblogs.com/hack0ne/p/4573168.html

lovecn commented 9 years ago

http://www.cnblogs.com/aaronjs/p/3279314.html jquery源码分析

lovecn commented 9 years ago

http://html2canvas.hertzen.com/

lovecn commented 9 years ago

https://github.com/WQTeam/web-storage-cache

lovecn commented 9 years ago

Chrome 浏览器文件关联调试方法 http://acwong.org/2015/05/26/chrome-file-associations-debugging/

lovecn commented 9 years ago

node-socket实现web的即时聊天系统http://www.xiabingbao.com/node/2015/04/06/node-socket/#top

lovecn commented 9 years ago

RGB颜色查询对照表http://www.114la.com/other/rgb.htm

lovecn commented 9 years ago

html5实现图片预览和查看原图http://www.xiabingbao.com/html5/2015/05/20/html5-filereader-natural

lovecn commented 9 years ago

react_native入门 http://vczero.github.io/react_native/%E7%AC%AC1%E7%AF%87hello%20react-native.html