javascript 易错点、难点笔记

前端开发 作者: 2024-08-25 22:05:01
本文主要记录在学习过程中遇到的JavaScript难点或者容易疏忽的细节,也方便自己日后翻阅学习。 1、arr.length + arr.length 是一种鸭式辨型的判断方法。这句话包含两层意思:
arr.length === + arr.length
  • arr.length是一个Number(可以试一下x === +x)
var arr = "123";
var arr2 = [1,2,3];
arr.length === + arr.length; //true
arr2.length === + arr2.length; true
Object.prototype.toString.call(arr)==='[object Array]'
    var s=Array(5);
    for(var i=0;i<s.length;i++)
    console.log(s.length);5 5 5 5 5

    var arr= new Array(5var i=0;i<arr.length;i++)
    console.log(arr.length);5 5 5 5 5
var undefinedBackup = undefined;
undefined = 1 显示"undefined"
console.log(typeof undefinedBackup);  
 在IE5.5~8中显示"number",其他浏览器中则显示"undefined"
console.log(typeof undefined);
var myUndefined;
console.log(typeof myUndefined);  显示"undefined"
var getUndefined = function(undefined){
  return undefined;
};
var myUndefined = getUndefined();
 或通过arguments获取
(){
   arguments[arguments.length];
};
(){};
var myUndefined = getUndefined();


var myUndefined1 = {}[''];
var myUndefined2 = [][0];
<!DOCTYPE html>
<html>        
    </body>
    div id="id"></divscript>
        var div=document.createElement("div);
        console.log(div.ownerDocument===document)
        console.log(div.ownerDocument.getElementById(id))
    >
 Strictly check a list of variable types against a list of arguments
 strict( types,args ) {

     Make sure that the number of types and args matches
    if (  types.length != args.length ) {
         If they do not,throw a useful exception
        throw "Invalid number of arguments. Expected " + types.length +
            ",received " + args.length + " instead.";
    }

     Go through each of the arguments and check their types
    for ( var i = 0; i < args.length; i++ ) {
        // 
        if ( args[i].constructor != types[i] ) {
            throw "Invalid argument type. Expected " + types[i].name +
                ",received " + args[i].constructor.name + " instead.";
        }
    }
}

 A simple function for printing out a list of users
 userList( prefix,num,users ) {
     Make sure that the prefix is a string,num is a number,
     and users is an array
    strict( [ String,Number,Array ],arguments );

     Iterate up to 'num' users
    var i = 0; i < num; i++ Displaying a message about each user
        alert( prefix + ": " + users[i] );
    }
}
 A generic function for displaying a delayed alert message
 delayedAlert( msg,time ) {
     Initialize an enclosed callback
    setTimeout((){
         Which utilizes the msg passed in from the enclosing function
        alert( msg );
    },time );
}
var obj = {
    yes:  this == obj
        this.val = true;
    },no: false;
    }
};

 We see that there is no val property in the 'obj' object
console.log( obj.val == null );true

 We run the yes function and it changes the val property
// associated with the 'obj' object
obj.yes();函数执行后,才会添加新的属性
console.log( obj.val == true ); However,we now point window.no to the obj.no method and run it
window.no = obj.no;
window.no();

 This results in the obj object staying the same (as the context was switched to the window object)
console.log( obj.val ==  and window val property getting updated.
console.log( window.val == false );true
        var data={0:"1",length:1};
        var arr2=Array.prototype.slice.call(data,0);
        console.log(arr2);  [1]

        var data={0:"1"[]

        );
        console.log(arr2.length);   2
        console.log(arr2[1]);       undefined
        console.log(arr2[0]);       1

        var data={t:"1",length:"2"2
        console.log(arr2[0]);       undefined    
new Date().getYear();    //116
new Date().getFullYear();    2016
 var str = "abcdefg";  
str.split("").reverse().join("")
#tagContainer div:hover {
background-color: red;
cursor: pointer;
}
#tagContainer div:hover:before {
content: "点击删除";
}
.tag-list li:hover {background-color: #fe0200;}
.tag-list li .delect {display: none;margin-right: 5px;}
.tag-list li:hover .delect {display: inline-block;}
//js tagLiNode.innerHTML = "<span class = 'delect'>删除</span><span class = 'ivalue'>"+inputValue+"</span>";
EventUtil.on(inputTag,'keyup',addtagNumkeyHandle);
function addtagNumkeyHandle(event){
     for (var i = 0; i < tagNum.childNodes.length; i++){
        tagNum.childNodes[i] = i;
        fn(i);
    }
}
function fn(i){
    var old = tagNum.childNodes[i].innerHTML;
    tagNum.childNodes[i].onmouSEOver = function (){
        this.innerHTML = '点击删除' + old;
        this.style.background = '#f00';
    };
    tagNum.childNodes[i].onmouSEOut = function (){
        this.innerHTML = old;
        this.style.background = '#8DC9FB';
    };
    tagNum.childNodes[i].onclick = function (){
        this.parentNode.removeChild(this);
        for (var j = 0; j < arr.length; j++){
            console.log(old,arr[j]);
            arrDelJ(old,j);
        }
        console.log(old,arr,json);
    }
}
//textInput事件处理程序,传入event,可以获取event.data,即刚刚按下的字符是什么。
function addtextHandle(event) {
    event=EventUtil.getEvent(event);
    if (pattern.test(event.data)){
        inputTagValue=inputTag.value.split(pattern1);
        renderdata(tagNum,inputTagValue);
        inputTag.value='';
        event.data='';
    }
}
//刚开始绑定的是keypress,一直不对,后面采用keyup就好多了。原因在于keypress只是键盘按下去这个事件响应了,
//但是keyup的话此时输入的值已经显示在input的当中了,这时我们就可以做清理工作了。
function addtagNumkeyHandle(event){
    event=EventUtil.getEvent(event);
    if (event.keyCode==13){//如果按下的是回车键,就将上述结果输入。
        inputTagValue=inputTag.value.split(pattern);
        renderdata(tagNum,inputTagValue);
        inputTag.value='';
    }
    inputTagValue=inputTag.value.split(pattern);
    if(inputTagValue[1]=="" ){
        inputTagValue=inputTag.value.split(pattern);
        renderdata(tagNum,inputTagValue);
        inputTag.value='';
    }
    
}

 

  •     非数组对象的属性不能保证以特定的顺序出现在序列化后的字符串中。
  •     布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值。
  •     undefined、任意的函数以及 symbol 值,在序列化过程中会被忽略(出现在非数组对象的属性值中时)或者被转换成 null(出现在数组中时)。
  •     所有以 symbol 为属性键的属性都会被完全忽略掉,即便 replacer 参数中强制指定包含了它们。
  •     不可枚举的属性会被忽略
JSON.stringify({});                         '{}'
JSON.stringify(true);                       'true'
JSON.stringify("foo");                      '"foo"'
JSON.stringify([1,"false",false]);        '[1,false]'
JSON.stringify({ x: 5 });                   '{"x":5}'

JSON.stringify({x: 5,y: 6});              
 '{"x":5,"y":6}' 或者 '{"y":6,"x":5}' 都可能
JSON.stringify([new Number(1),1)">new String("false"),1)">new Boolean()]);
)});
 '{}'
JSON.stringify([undefined,Object,Symbol("")]);          
 '[null,null,null]'
JSON.stringify({[Symbol("foo")]: "foo"});                 
 '{}'
JSON.stringify({[Symbol.for("foo")]: "foo"},[Symbol.for("foo" (k,v) {
  if (typeof k === "symbol"){
    return "a symbol";
  }
});

 '{}'  

 不可枚举的属性默认会被忽略:
JSON.stringify( Object.create(null,{ x: { value: 'x',enumerable: false },y: { value: 'y',1)"> } }) );
 '{"y":"y"}'
JSON.parse('{}');               {}
JSON.parse('true');             true
JSON.parse('"foo"');            "foo"
JSON.parse('[1,5,"false"]');  [1,"false"]
JSON.parse('null');             null
JSON.parse('{"name": "asad"}') {name: "asad"}
var arr=[],s;
console.log(arr==0);          true
console.log(arr==null);        false
console.log(arr==undefined);false
console.log(arr=="");        true
console.log(0==false
console.log(0==undefined);    false
console.log(null==undefined);true
console.log(""==undefined);    false
console.log(s==undefined)    true
console.log(s==0)            false
if(typeof(global) !== 'undefined' && typeof(window) === 'undefined') {
    juicer.set('cache',1)">);
}
 字符串转义
 stringify (code) {
    return "'" + code
     单引号与反斜杠转义
    .replace(/('|\\)/g,'\\$1')
     换行符转义(windows + linux)
    .replace(/\r/g,'\\r')
    .replace(/\n/g,'\\n') + "'";
}
 char-->ascii
 ascii-->char
   String.fromCharCode(a);
    var reg = new RegExp("^\\d+$"var reg1 = new RegExp("^\d+$"var d= /^\d+$/
    console.log(reg)               /^\d+$/
    console.log(reg1)              /^d+$/
    console.log(d)                 /^\d+$/
    console.log(reg.test(12))      true
    console.log(reg1.test(12))     flase
    console.log(d.test(12))        true
!(ob){
    ob.ob=this.a=3;
        console.log(this);  window
    }
}(window)
ob();
console.log(a);
 Bomb() {
  this.message = 'Boom!';
}

Bomb.prototype.explode = () {
  console.log(this.message);
};

var bomb = new Bomb();

var message = 'window';

setTimeout(bomb.explode.bind(bomb),1000); Boom!
setTimeout(bomb.explode,1000);  window
var i=0;
console.log(i++,++i,i++,i); //0 2 3 3 4
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68624.html