必威-必威-欢迎您

必威,必威官网企业自成立以来,以策略先行,经营致胜,管理为本的商,业推广理念,一步一个脚印发展成为同类企业中经营范围最广,在行业内颇具影响力的企业。

迷失网络,数组1和数组2分别调用remove()方法

2019-10-05 05:36 来源:未知

JavaScript 原生对象及扩充

2016/09/26 · JavaScript · 对象

初稿出处: trigkit4   

近些日子在JavaSript进行Array操作的时候发掘未有去除节点的主意,而自己要落实的功能必要持续调用删除节点的秘诀,查找了相关材质发掘能够接纳prototype属性给Array扩大删除节点的措施,何况该办法同Array本身具有的push()、pop()、reverse()、slice()、sort()、join()等艺术一样采取。

1、 javascript的typeof重返哪些数据类型

alert(typeof [1, 2]);    //object 

alert(typeof 'leipeng');    //string   

var i = true;    alert(typeof i);  //boolean   

alert(typeof 1);    //number   

var a;    alert(typeof a);  //undefined 

function a(){;};    alert(typeof a)  //function

var a = null;alert(typeof a); //object 解释:null是七个独有三个值的数据类型,那几个值正是null。表示一个空指针对象,所以用typeof检查实验会重临”object ”

/****************************************************************
    JScript 常用运营库    Version 1.11
                    
    作者    :    Lostinet[迷失互连网]
    Email    :    lostinet@chongjian.com
****************************************************************/

咱俩知晓,JavaScript中检查测量试验对象类型的运算符有:typeof、instanceof,还应该有对象的constructor属性:

松开对象与原生对象

内置(Build-in)对象与原生(Naitve)对象的差异在于:前面二个总是在发动机初步化阶段就被创立好的指标,是前面一个的贰个子集;而后面一个包涵了有的在运作进度中动态创设的对象。

图片 1

 

function LostinetJScriptRuntimeLibrary(){}

1) typeof 运算符 typeof 是一元运算符,再次回到结果是三个验证运算数类型的字符串。如:"number","string","boolean","object","function","undefined"(可用以推断变量是还是不是留存)。 但 typeof 的技艺有限,其对于Date、RegExp类型重返的都以"object"。如:

原生对象(New后的指标)

ECMA-262 把原生对象(native object)定义为“独立于宿主际遇的 ECMAScript 完结提供的指标”。包涵如下:

Object、Function、Array、String、Boolean、Number、Date、RegExp、Error、EvalError、RangeError、ReferenceError、SyntaxError、TypeError、U奇骏IError、ActiveXObject(服务器方面)、Enumerator(集合遍历类)、RegExp(正则表明式)

1
Object、Function、Array、String、Boolean、Number、Date、RegExp、Error、EvalError、RangeError、ReferenceError、SyntaxError、TypeError、URIError、ActiveXObject(服务器方面)、Enumerator(集合遍历类)、RegExp(正则表达式)

由此能够看出,轻巧的话,原生对象便是 ECMA-262 定义的类(援用类型)。

来源:

代码1

2、例举3种强制类型转变和2种隐式类型调换?

强制(parseInt() , parseFloat() , Number() )

隐式(== ,!!)

/****************************************************************
    Global
****************************************************************/
function Global(){}
function Global.GetUndefined(){}
function Global.ValueOf(unknown){
    if(Global.IsUndefined(unknown))return Global.GetUndefined();
    try{
        return unknown.valueOf();
    }catch(x){}
    return unknown;
}

typeof {}; // "object"
typeof []; // "object"
typeof new Date(); // "object"

置于对象(无需New)

概念:由ECMAScript完成提供的对象,独立于宿主情状,在四个本子程序执行的初阶处。

:各个内置对象(built-in object)都以原生对象(Native Object),一个内置的构造函数是三个放权的靶子,也是贰个构造函数。

来源:

举个栗子:

Native objects: Object (constructor), Date, Math, parseInt, eval。 string 方法例如 indexOf 和 replace, array 方法, ... Host objects (假定是浏览器遭受): window, document, location, history, XMLHttpRequest, setTimeout, getElementsByTagName, querySelectorAll, ...

1
2
3
Native objects: Object (constructor), Date, Math, parseInt, eval。 string 方法比如 indexOf 和 replace, array 方法, ...
 
Host objects (假定是浏览器环境): window, document, location, history, XMLHttpRequest, setTimeout, getElementsByTagName, querySelectorAll, ...

ECMA-262][2 只定义了多个新的放权对象,即 GlobalMath (它们也是原生对象,依照定义,每一个内置对象都以原生对象)。

以下是ECMA-262概念的内置对象(built-in):

global、Object、Function、Array、String、Boolean、Number、Math、Date、RegExp、JSON、Error对象(Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError 和URIError)

1
global、Object、Function、Array、String、Boolean、Number、Math、Date、RegExp、JSON、Error对象(Error,   EvalError, RangeError, ReferenceError,   SyntaxError, TypeError 和URIError)

图片 2

作者们也足以修改内置对象的原型

JavaScript

if (!Array.prototype.forEach) { Array.prototype.forEach = function(fn){ for ( var i = 0; i < this.length; i++ ) { fn( this[i], i, this ); } }; } ["a", "b", "c"].forEach(function(value, index, array){ assert( value, "Is in position " + index + " out of " + (array.length - 1) ); });

1
2
3
4
5
6
7
8
9
10
11
if (!Array.prototype.forEach) {
  Array.prototype.forEach = function(fn){
    for ( var i = 0; i < this.length; i++ ) {
      fn( this[i], i, this );
    }
  };
}
["a", "b", "c"].forEach(function(value, index, array){
  assert( value, "Is in position " + index + " out of " + (array.length - 1) );
});

如上代码将出口:

PASS Is in position 0 out of 2 PASS Is in position 1 out of 2 PASS Is in position 2 out of 2

1
2
3
PASS Is in position 0 out of 2
PASS Is in position 1 out of 2
PASS Is in position 2 out of 2

只顾:扩充原型是很凶险的:

JavaScript

Object.prototype.keys = function(){ var keys = []; for ( var i in this ) keys.push( i ); return keys; }; var obj = { a: 1, b: 2, c: 3 }; assert( obj.keys().length == 3, "We should only have 3 properties." ); delete Object.prototype.keys;

1
2
3
4
5
6
7
8
9
10
11
12
Object.prototype.keys = function(){
  var keys = [];
  for ( var i in this )
    keys.push( i );
  return keys;
};
var obj = { a: 1, b: 2, c: 3 };
assert( obj.keys().length == 3, "We should only have 3 properties." );
delete Object.prototype.keys;

输出: FAIL We should only have 3 properties.

假设不是有非凡供给而去增加原生对象和原型(prototype)的做法是不好的

JavaScript

//不要这么做 Array.prototype.map = function() { // code };

1
2
3
4
//不要这样做
Array.prototype.map = function() {
    // code
};

唯有那样做是值得的,例如,向一些旧的浏览器中加多一些ECMAScript5中的方法。
在这种情况下,大家日常那样做:

XHTML

<script type="text/javascript"> if (!Array.prototype.map) { Array.prototype.map = function() { //code }; } </script>

1
2
3
4
5
6
7
<script type="text/javascript">
    if (!Array.prototype.map) {
        Array.prototype.map = function() {
            //code
        };
    }
</script>

[javascript]  

3、split()、join() 的区别

后边三个是切割成数组的款式,前者是将数组转变来字符串

function Global.ToString(unknown){
    if(Global.IsUndefined(unknown))return "";
    if(Global.IsJScriptObject(unknown))
    {
        try{
            return String.Convert(unknown.toString());
        }catch(x){}
    }
    return String.Convert(unknown);
}
function Global.IsBlank(unknown){
    switch(typeof(unknown))
    {
    case "undefined":return true;
    case "string":return unknown=="";
    case "number":return unknown==0;
    case "object":return unknown==null;
    case "function":return false;
    default:return unknown?false:true;
    }
}
function Global.IsJScriptType(unknown)
{
    switch(typeof(unknown))
    {
    case "object":
        return Global.IsJScriptObject(unknown);
    case "function":
    case "string":
    case "number":
    case "boolean":
    case "undefined":
        return true;
    default:
        return false;
    }
}
function Global.IsJScriptObject(unknown)
{
    if(typeof(unknown)=="function")return true;
    if(typeof(unknown)!="object")return false;
    try{
        return typeof(unknown.constructor)=="function";
    }catch(x){
    }
    return false;
}
function Global.ThrowError(msg){
    throw(new Error(-1,msg));
}
/****************************************************************
    Object
****************************************************************/

据此它只在分别对象和原始类型的时候才有用。要区一种对象类型和另一种对象类型,必得选取别的的不二等秘书技。如:instanceof 运算符或对象的 constructor 属。

用原型扩充对象

对js原生对象的庞大无非正是往prototype里登记,举个例子,大家可未来String对象里扩张ltrim,rtrim等措施。js种种对象都卫冕自Object,並且,对象和任何品质都通过prototype指标来接二连三。通过prototype指标,大家得以扩大任何对象,包罗内建的靶子,如StringDate

Array.prototype.remove = function (dx) {  

4、数组方法 pop()  push()  unshift()  shift()

push() 后面部分加多      pop() 尾部剔除

unshift() 底部增添  shift() 尾部剔除

map() : 遍历数组中的成分, 重返三个新数组(包罗回调函数再次回到的数量)

filter():遍历数组中的成分, 重临多少个新数组(包蕴回调函数再次回到true的因素)

/*
unknown,function,ActiveXObject等会被以为是undefined
除开Object和Array,其余object类型的子属性会被忽视
自定义的constructor会自动转为Object
*/
//供给优化
function Object.Encode(v)
{
    var Encoders={"unknown":_unknown,"object":_object,"function":_function,"string":_string,"number":_number,"boolean":_boolean,"undefined":_undefined};
    return InnerEncode(v);
    function InnerEncode(v)
    {
        var der=Encoders[typeof(v)];
        if(der)
            return der(v);
        return _undefined(v);
    }
    function EncodeString(v){
        v=String.Convert(v);
        v=v.replace(/&/g,"&0");
        v=v.replace(/=/g,"&1");
        v=v.replace(/:/g,"&2");
        v=v.replace(/,/g,"&3");
        return v;
    }
    function _unknown(v)
    {
        return _undefined(v);
    }
    function _object(v)
    {
        if(!Global.IsJScriptObject(v))
            return _undefined(v);
        switch(v.constructor)
        {
        case Array:        return _Array(v);
        case Date:        return _Date(v);
        case String:    return _String(v);
        case Number:    return _Number(v);
        case Boolean:    return _Boolean(v);
        case RegExp:    return _RegExp(v);
        case Object:
        default:
            return _Object(v);
        }
        function _Object(v)
        {
            var str="object_Object=";
            var arr=[];
            for(var i in v)
            {
                if(Global.IsJScriptType(v[i])&&typeof(v[i])!="function")
                    arr[arr.length]=EncodeString(EncodeString(i)+":"+EncodeString(InnerEncode(v[i])));
            }
            return str+arr.join(",");
        }
        function _Array(v)
        {
            var str="object_Array=";
            var arr=[];
            for(var i in v)
            {
                if(Global.IsJScriptType(v[i])&&typeof(v[i])!="function")
                    arr[arr.length]=EncodeString(EncodeString(i)+":"+EncodeString(InnerEncode(v[i])));
            }
            return str+arr.join(",");
        }
        function _Date(v){return "object_Date="+v.getTime();}
        function _String(v){return "object_String="+EncodeString(v);}
        function _Number(v){return "object_Number="+EncodeString(v);}
        function _Boolean(v){return "object_Boolean="+EncodeString(v.ToString());}
        function _RegExp(v)
        {
            return "object_RegExp="+
                EncodeString(
                    "p:"+EncodeString(v)+
                    "i:"+EncodeString(Boolean.ToString(v.ignoreCase))+
                    "g:"+EncodeString(Boolean.ToString(v.global))
                );
        }
    }
    function _function(v){return _undefined(v);}
    function _string(v){return "string="+EncodeString(v);}
    function _number(v){return "number="+EncodeString(v);}
    function _boolean(v){return "boolean="+EncodeString(v.ToString());}
    function _undefined(v){return "undefined=undefined";}
}
//需求优化
function Object.Decode(s)
{
    s=String.Convert(s);
    var Decoders={"object_Object":_object_Object,"object_Array":_object_Array,"object_Date":_object_Date,"object_String":_object_String,"object_Number":_object_Number,"object_Boolean":_object_Boolean,"object_RegExp":_object_RegExp,"string":_string,"number":_number,"boolean":_boolean,"undefined":_undefined};
    return InnerDecode(s);
    function InnerDecode(s)
    {
        s=String.Convert(s);
        var arr=s.split("=");
        var type=arr[0];
        var der=Decoders[type];
        if(der)
            return der(String.Convert(arr[1]));
        return _undefined(String.Convert(arr[1]));
    }
    function DecodeString(v){
        v=String.Convert(v);
        v=v.replace(/&3/g,",");
        v=v.replace(/&2/g,":");
        v=v.replace(/&1/g,"=");
        v=v.replace(/&0/g,"&");
        return v;
    }
    function _object_Object(ss)
    {
        var obj=new Object();
        var arr=ss.split(",");
        for(var i=0;i<arr.length;i++)
        {
            var arr2=DecodeString(arr[i]).split(":");
            var index=DecodeString(arr2[0]);
            if(index=="")break;
            obj[index]=InnerDecode(DecodeString(arr2[1]));
        }
        return obj;
    }
    function _object_Array(ss)
    {
        var obj=new Array();
        var arr=ss.split(",");
        for(var i=0;i<arr.length;i++)
        {
            var arr2=DecodeString(arr[i]).split(":");
            var index=DecodeString(arr2[0]);
            if(index=="")break;
            obj[index]=InnerDecode(DecodeString(arr2[1]));
        }
        return obj;
    }
    function _object_Date(ss){return Date.Convert(Number.Convert(DecodeString(ss)));}
    function _object_String(ss){return new String(String.Convert(DecodeString(ss)));}
    function _object_Number(ss){return new Number(Number.Convert(DecodeString(ss)));}
    function _object_Boolean(ss){return new Boolean(Boolean.ConvertFromString(DecodeString(ss)));}
    function _object_RegExp(ss)
    {
        var obj=new Object();
        var arr=ss.split(",");
        for(var i=0;i<arr.length;i++)
        {
            var arr2=DecodeString(arr[i]).split(":");
            var index=DecodeString(arr2[0]);
            if(index=="")break;
            obj[index]=InnerDecode(DecodeString(arr2[1]));
        }
        var re=new RegExp();
        re.pattern=String.Convert(obj.p);
        re.ignoreCase=Boolean.Convert(obj.i);
        re.global=Boolean.Convert(obj.g);
        return re;
    }
    function _string(ss){return String.Convert(DecodeString(ss));}
    function _number(ss){return Number.Convert(DecodeString(ss));}
    function _boolean(ss){return Boolean.ConvertFromString(DecodeString(ss));}
    function _undefined(ss){return Global.GetUndefined();}
}

2)instanceof 运算符。 instanceof 运算符需求其左边手的运算数是三个对象,左边的运算数是对象类的名字或构造函数。倘若object 是 class 或构造函数的实例,则 instanceof 运算符再次回到 true。假如object 不是钦赐类或函数的实例,或然 object 为 null,则赶回 false。如:

String对象的恢宏

JavaScript

<script type="text/javascript"> if(typeof String.prototype.ltrim=='undefined'){ String.prototype.ltrim = function(){ var s = this; s = s.replace(/^s*/g, ''); return s; } } if(typeof String.prototype.rtrim=='undefined'){ String.prototype.rtrim = function(){ var s = this; s = s.replace(/s*$/g, ''); return s; } } if(typeof String.prototype.trim=='undefined'){ String.prototype.trim = function(){ return this.ltrim().rtrim(); } } if(typeof String.prototype.htmlEncode=='undefined'){ String.prototype.htmlEncode = function(encodeNewLine){//encodeNewLine:是否encode换行符 var s = this; s = s.replace(/&/g, '&'); s = s.replace(/</g, '<'); s = s.replace(/>/g, '>'); s = s.replace(/'/g, '"'); if(encodeNewLine){ s = s.replace(/rn/g, '<br />'); s = s.replace(/r/g, '<br />'); s = s.replace(/n/g, '<br />'); } return s; } } </script>

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
<script type="text/javascript">
    if(typeof String.prototype.ltrim=='undefined'){
        String.prototype.ltrim = function(){
            var s = this;
            s = s.replace(/^s*/g, '');
            return s;
        }
    }
 
    if(typeof String.prototype.rtrim=='undefined'){
        String.prototype.rtrim = function(){
            var s = this;
            s = s.replace(/s*$/g, '');
            return s;
        }
    }
 
    if(typeof String.prototype.trim=='undefined'){
        String.prototype.trim = function(){
            return this.ltrim().rtrim();
        }
    }
 
    if(typeof String.prototype.htmlEncode=='undefined'){
        String.prototype.htmlEncode = function(encodeNewLine){//encodeNewLine:是否encode换行符
            var s = this;
            s = s.replace(/&/g, '&amp;');
            s = s.replace(/</g, '&lt;');
            s = s.replace(/>/g, '&gt;');
            s = s.replace(/'/g, '&quot;');
            if(encodeNewLine){
                s = s.replace(/rn/g, '<br />');
                s = s.replace(/r/g, '<br />');
                s = s.replace(/n/g, '<br />');
            }
            return s;
        }
    }
</script>

        if (isNaN(dx) || dx > this.length) { return false; }  

5、IE和DOM事件流的界别

1.实践种种不雷同、

2.参数差异

3.事件加不加on

4.this指向难点

function Object.EncodeJScript(v)
{
    if(Boolean.IsFalse(Global.IsJScriptType(v)))
    {
        return _undefined(v);
    }
    return eval("_"+typeof(v))(v);
    function _object(v)
    {
        if(Boolean.IsFalse(Global.IsJScriptObject(v)))return _undefined(v);
        switch(v.constructor)
        {
        case Object:    return _Object(v);
        case Array:        return _Array(v);
        case Date:        return _Date(v);
        case String:    return _String(v);
        case Number:    return _Number(v);
        case Boolean:    return _Boolean(v);
        case RegExp:    return _RegExp(v);
        default:
            if(typeof(v.constructor)=="function")return _Object(v);
        }
        return _undefined(v);
    }
    function _Object(v)
    {
        var arr=[];
        for(var i in v)
        {
            if(typeof(v[i])!="function"&&Global.IsJScriptType(v[i]))
                arr[arr.length]='"'+String.EncodeJScript(i)+'":'+eval("_"+typeof(v[i]))(v[i]);
        }
        return "{"+arr.join(",")+"}";
    }
    function _Array(v)
    {
        var arr=[];
        for(var i in v)
        {
            if(typeof(v[i])!="function"&&Global.IsJScriptType(v[i]))
                arr[arr.length]=eval("_"+typeof(v[i]))(v[i]);
        }
        return "["+arr.join(",")+"]";
    }
    function _Date(v){return "new Date(""+String.EncodeJScript(new Date().toUTCString())+"")";}
    function _String(v){return "new String(""+String.EncodeJScript(v)+"")";}
    function _Number(v){return "new Number("+Number.Convert(v)+")";}
    function _Boolean(v){return "new Boolean("+Boolean.ToString(v)+")";}
    function _RegExp(v){return "new RegExp("+v+")";}    
    function _function(v){return "(function(){})()";}
    function _string(v){return """+String.EncodeJScript(v)+"""}
    function _number(v){return String.Convert(v);}
    function _boolean(v){return Boolean.ToString(v);}
    function _undefined(v){return "(function(){})()";}
    function _unknown(s){return "(function(){})()";}
}
function Object.DecodeJScript(s)
{
    s=String.Convert(s);
    if(s=="")return null;
    if(s=="undefined")return GetUndefined();
    var o=null;
    try{
        eval("o="+s);
    }catch(x){
        throw(new Error(-1,"Object.DecodeJScript不能够反编码n"+x.description+"n原代码是:n"+s));
    }
    return o;
}

[] instanceof Array; // true
[] instanceof Object; // true
[] instanceof RegExp; // false
new Date instanceof Date; // true

Date对象的庞大

getDaysInMonth:获取某月有多少天

JavaScript

Date.getDaysInMonth = function (year, month) { var days = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31 break; case 4: case 6: case 9: case 11: days = 30; break; case 2: if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) days = 29; else days = 28; break; } return days; } if (typeof Date.prototype.format == 'undefined') { Date.prototype.format = function (mask) { var d = this; var zeroize = function (value, length) { if (!length) length = 2; value = String(value); for (var i = 0, zeros = ''; i < (length - value.length); i++) { zeros += '0'; } return zeros + value; }; return mask.replace(/"[^"]*"|'[^']*'|b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])1?|[lLZ])b/g, function ($0) { switch ($0) { case 'd': return d.getDate(); case 'dd': return zeroize(d.getDate()); case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()]; case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()]; case 'M': return d.getMonth() + 1; case 'MM': return zeroize(d.getMonth() + 1); case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()]; case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()]; case 'yy': return String(d.getFullYear()).substr(2); case 'yyyy': return d.getFullYear(); case 'h': return d.getHours() % 12 || 12; case 'hh': return zeroize(d.getHours() % 12 || 12); case 'H': return d.getHours(); case 'HH': return zeroize(d.getHours()); case 'm': return d.getMinutes(); case 'mm': return zeroize(d.getMinutes()); case 's': return d.getSeconds(); case 'ss': return zeroize(d.getSeconds()); case 'l': return zeroize(d.getMilliseconds(), 3); case 'L': var m = d.getMilliseconds(); if (m > 99) m = Math.round(m / 10); return zeroize(m); case 'tt': return d.getHours() < 12 ? 'am' : 'pm'; case 'TT': return d.getHours() < 12 ? 'AM' : 'PM'; case 'Z': return d.toUTCString().match(/[A-Z]+$/); // Return quoted strings with the surrounding quotes removed default: return $0.substr(1, $0.length - 2); } }); }; }

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
Date.getDaysInMonth = function (year, month) {
            var days = 0;
            switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    days = 31
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    days = 30;
                    break;
                case 2:
                    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
                        days = 29;
                    else
                        days = 28;
                    break;
            }
            return days;
        }
 
        if (typeof Date.prototype.format == 'undefined') {
            Date.prototype.format = function (mask) {
 
                var d = this;
 
                var zeroize = function (value, length) {
 
                    if (!length) length = 2;
 
                    value = String(value);
 
                    for (var i = 0, zeros = ''; i < (length - value.length); i++) {
 
                        zeros += '0';
 
                    }
 
                    return zeros + value;
 
                };
 
                return mask.replace(/"[^"]*"|'[^']*'|b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])1?|[lLZ])b/g, function ($0) {
 
                    switch ($0) {
 
                        case 'd': return d.getDate();
 
                        case 'dd': return zeroize(d.getDate());
 
                        case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
 
                        case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
 
                        case 'M': return d.getMonth() + 1;
 
                        case 'MM': return zeroize(d.getMonth() + 1);
 
                        case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
 
                        case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
 
                        case 'yy': return String(d.getFullYear()).substr(2);
 
                        case 'yyyy': return d.getFullYear();
 
                        case 'h': return d.getHours() % 12 || 12;
 
                        case 'hh': return zeroize(d.getHours() % 12 || 12);
 
                        case 'H': return d.getHours();
 
                        case 'HH': return zeroize(d.getHours());
 
                        case 'm': return d.getMinutes();
 
                        case 'mm': return zeroize(d.getMinutes());
 
                        case 's': return d.getSeconds();
 
                        case 'ss': return zeroize(d.getSeconds());
 
                        case 'l': return zeroize(d.getMilliseconds(), 3);
 
                        case 'L': var m = d.getMilliseconds();
 
                            if (m > 99) m = Math.round(m / 10);
 
                            return zeroize(m);
 
                        case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
 
                        case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
 
                        case 'Z': return d.toUTCString().match(/[A-Z]+$/);
 
                            // Return quoted strings with the surrounding quotes removed    
 
                        default: return $0.substr(1, $0.length - 2);
 
                    }
 
                });
 
            };
        }

        for (var i = 0, n = 0; i < this.length; i++) {  

6、IE和正式下有哪些包容性的写法

var ev = ev || window.event

document.documentElement.clientWidth || document.body.clientWidth

var target = ev.srcElement||ev.target

/****************************************************************
    Function
****************************************************************/

因而,能够用instanceof运算符来决断目的是还是不是为数组类型:

动用原生js达成复制对象及扩充

jQueryextend()措施能很方便的贯彻扩充对象方法,这里要落到实处的是:使用原生js兑现复制对象,扩充对象,类似jQuery中的extend()方法

JavaScript

var obj1 = { name : 'trigkit4', age : 22 }; var obj2 = { name : 'frank', age : 21, speak : function(){ alert("hi, I'm + name "); } }; var obj3 ={ age : 20 }; function cloneObj(oldObj) { //复制对象方法 if (typeof(oldObj) != 'object') return oldObj; if (oldObj == null) return oldObj; var newObj = Object(); for (var i in oldObj) newObj[i] = cloneObj(oldObj[i]); return newObj; } function extendObj() { //扩大对象 var args = arguments;//将传递过来的参数数组赋值给args变量 if (args.length < 2) return; var temp = cloneObj(args[0]); //调用复制对象方法 for (var n = 1; n < args.length; n++) { for (var i in args[n]) { temp[i] = args[n][i]; } } return temp; } var obj =extendObj(obj1,obj2,obj3); console.log(obj);//{ name: 'frank', age: 20, speak: [Function] } console.log(obj1);//{ name: 'trigkit4', age: 22 } console.log(obj2);//{ name: 'frank', age: 21, speak: [Function] } console.log(obj3);//{ age: 20 }

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
var obj1 = {
    name : 'trigkit4',
    age : 22
};
var obj2 = {
    name : 'frank',
    age : 21,
    speak : function(){
        alert("hi, I'm + name ");
    }
};
 
var obj3 ={
    age : 20
};
 
function cloneObj(oldObj) { //复制对象方法
    if (typeof(oldObj) != 'object') return oldObj;
    if (oldObj == null) return oldObj;
    var newObj = Object();
    for (var i in oldObj)
        newObj[i] = cloneObj(oldObj[i]);
    return newObj;
}
 
function extendObj() { //扩展对象
    var args = arguments;//将传递过来的参数数组赋值给args变量
    if (args.length < 2) return;
    var temp = cloneObj(args[0]); //调用复制对象方法
    for (var n = 1; n < args.length; n++) {
        for (var i in args[n]) {
            temp[i] = args[n][i];
        }
    }
    return temp;
}
var obj =extendObj(obj1,obj2,obj3);
console.log(obj);//{ name: 'frank', age: 20, speak: [Function] }
console.log(obj1);//{ name: 'trigkit4', age: 22 }
console.log(obj2);//{ name: 'frank', age: 21, speak: [Function] }
console.log(obj3);//{ age: 20 }

            if (this[i] != this[dx]) {  

7、call和apply的区别

功用雷同, 都是将方今函数作为钦点对象的点子推行, 即函数中的this是点名对象

call(thisObj,arg1,arg2...)  //将全体参数叁个贰个传递步入

apply(thisObj,[argArray])  //将全部参数放在数组中传出

/*
主导公约!分化意有Function.prototype.XXX();
*/

function isArray(arr){
    return arr instanceof Array;
}

es5-safe 模块

es5-safe 模块里,仅扩展了能够较好达成的能够安枕而卧接纳的局地方法,蕴含:

JavaScript

Function.prototype.bind Object.create Object.keys Array.isArray Array.prototype.forEach Array.prototype.map Array.prototype.filter Array.prototype.every Array.prototype.some Array.prototype.reduce Array.prototype.reduceRight Array.prototype.indexOf Array.prototype.lastIndexOf String.prototype.trim Date.now

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Function.prototype.bind
Object.create
Object.keys
Array.isArray
Array.prototype.forEach
Array.prototype.map
Array.prototype.filter
Array.prototype.every
Array.prototype.some
Array.prototype.reduce
Array.prototype.reduceRight
Array.prototype.indexOf
Array.prototype.lastIndexOf
String.prototype.trim
Date.now

详情:

                this[n++] = this[i]  

8、哪些阻止事件冒泡和事件默许行为

//阻止事件冒泡

if(typeof ev.stopPropagation=='function') {  //标准的

              ev.stopPropagation();

} else { //非标准IE

              window.event.cancelBubble = true;

}

//阻止事件默许行为

return  false

/****************************************************************
    String
****************************************************************/
function String.Convert(v,dv)
{
    if(typeof(v)=="string")return v;
    if(typeof(dv)=="undefined")dv="";
    else dv=String.Convert(dv);    
    if(typeof(v)=="number")return v.toString();
    if(typeof(v)=="undefined")return dv;
    if(v===null)return dv;
    try{
        v=v+""
        if(v==="undefined")return dv;
        return String.Convert(v,dv);
    }catch(x){}
    return "[unconvertable]";
}
function String.ConvertArguments(args)
{
    if(typeof(args)!="object")
    {
        if(Global.IsBlank(String.ConvertArguments.caller))return "";
        args=String.ConvertArguments.caller.arguments;
    }
    return Array.ConvertArguments(args).join("");
}
function String.Random(count)
{
    var res="";
    for(var i=0;i<count;i++)
    {
        var t=(Math.random()*62*1000)%62;
        if(t<10)res+=String.fromCharCode(t+48);
        else if(t<36)res+=String.fromCharCode(t+55);
        else res+=String.fromCharCode(t+61);
    }
    return res;
}

3)constructor 属性。 JavaScript中,种种对象都有一个constructor属性,它援引了初叶化该目的的构造函数,常用于剖断未知对象的品种。如给定贰个求知的值 通过typeof运算符来剖断它是原来的值依然对象。如果是指标,就足以行使constructor属性来决断其体系。所以剖断数组的函数也得以这么写:

指标的创办

JavaScript 援助五连串型的目的:内部对象、生成的靶子、宿主给出的靶子(如 Internet 浏览器中的 windowdocument)以及ActiveX 对象(外部组件)。

Microsoft Jscript 提供了 11 个内部(或“内置”)对象。它们是Array、Boolean、Date、Function、Global、Math、Number、Object、RegExp、Error 以及 String 对象。每贰个指标有连锁的秘技和天性,

JavaScript中指标的创导有以下两种艺术:

(1)使用内置对象 (2)使用JSON符号 (3)自定义对象社团

1
2
3
(1)使用内置对象
(2)使用JSON符号
(3)自定义对象构造

            }  

//补满0
function String.prototype.ToStringByZero(count)
{
    var str=this;
    while(str.length<count)str="0"+str;
    return str;
}function String.ToStringByZero(str,count){return String.Convert(str).ToStringByZero(count);}

function isArray(arr){
    return typeof arr == "object" && arr.constructor == Array;
}

一、使用内置对象

JavaScript可用的放到对象可分为三种: 1,JavaScript语言原生对象(语言级对象),如String、Object、Function等; 2,JavaScript运转期的宿主对象(意况宿主级对象),如window、document、body等。

1
2
3
4
JavaScript可用的内置对象可分为两种:
 
1,JavaScript语言原生对象(语言级对象),如String、Object、Function等;
2,JavaScript运行期的宿主对象(环境宿主级对象),如window、document、body等。

        }  

9、 增加 删除 替换 插入到某些成分的点子

element.appendChild()

element.insertBefore()

element.replaceChild()

element.removeChild()

//编码SQL的常规字符串
function String.prototype.EncodeSQL()
{
    var str=this;
    str=str.replace(/x27/g,"''");
    return str;
}function String.EncodeSQL(str){return String.Convert(str).EncodeSQL();}
//用 Like 操作符时编码SQL
function String.prototype.EncodeSQLLike()
{
    var str=this;
    str=str.replace(/x60/g,"[`]");
    str=str.replace(/x7e/g,"[~]");
    str=str.replace(/x21/g,"[!]");
    str=str.replace(/x40/g,"[@]");
    str=str.replace(/x23/g,"[#]");
    str=str.replace(/x24/g,"[$]");
    str=str.replace(/x25/g,"[%]");
    str=str.replace(/x5e/g,"[^]");
    str=str.replace(/x26/g,"[&]");
    str=str.replace(/x2a/g,"[*]");
    str=str.replace(/x28/g,"[(]");
    str=str.replace(/x29/g,"[)]");
    str=str.replace(/x5f/g,"[_]");
    str=str.replace(/x2b/g,"[+]");
    str=str.replace(/x7c/g,"[|]");
    str=str.replace(/x2d/g,"[-]");
    str=str.replace(/x3d/g,"[=]");
    str=str.replace(/x5c/g,"[]");
    str=str.replace(/x5b/g,"[[]");
    str=str.replace(/x5d/g,"[]]");
    str=str.replace(/x3b/g,"[;]");
    str=str.replace(/x27/g,"''");//str=str.replace(/x27/g,"[']");// ' => ''
    str=str.replace(/x2c/g,"[,]");
    str=str.replace(/x2e/g,"[.]");
    str=str.replace(/x2f/g,"[/]");
    str=str.replace(/x7b/g,"[{]");
    str=str.replace(/x7d/g,"[}]");
    str=str.replace(/x3a/g,"[:]");
    //str=str.replace(/x22/g,"["]");
    str=str.replace(/x3c/g,"[<]");
    str=str.replace(/x3e/g,"[>]");
    str=str.replace(/x3f/g,"[?]");
    return str;
}function String.EncodeSQLLike(str){return String.Convert(str).EncodeSQLLike();}

众多气象下,我们能够使用instanceof运算符或对象的constructor属性来检查测验对象是不是为数组。比方比比较多JavaScript框架正是选用那二种艺术来剖断目的是或不是为数组类型。 可是检查评定在跨框架(cross-frame)页面中的数组时,会失败。原因就是在分化框架(iframe)中成立的数组不会互相分享其prototype属性。举个例子:

嵌入对象列表

Array Boolean Date Error EvalError Function Infinity JSON Map Math NaN Number Object ParallelArray Promise Proxy RegExp Set String Symbol SyntaxError Uint32Array WeakSet decodeURI decodeURIComponent() encodeURI() encodeURIComponent() escape()已废弃 eval() isFinite() isNaN() null parseFloat parseInt undefined

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
Array
Boolean
Date
Error
EvalError
Function
Infinity
JSON
Map
Math
NaN
Number
Object
ParallelArray
Promise
Proxy
RegExp
Set
String
Symbol
SyntaxError
Uint32Array
WeakSet
decodeURI
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()已废弃
eval()
isFinite()
isNaN()
null
parseFloat
parseInt
undefined

以上资料来源:

        this.length -= 1  

10、javascript的松开对象和宿主对象

内置对象为Object, Array, Function, Date, Math等

宿主为浏览器自带的window 等

//编码成VBScript字符串,两侧的引号已经加了""
function String.prototype.EncodeVBScript()
{
    var str=this;
    str=str.replace(/x22/g,"""");
    str=str.replace(/n/g,"" & vbNewline & _n"");
    str=str.replace(/r/g,"");
    return "_n""+str+""";
}function String.EncodeVBScript(str){return String.Convert(str).EncodeVBScript();}

复制代码 代码如下:

自定义对象组织

创造高端对象组织有二种方式:使用“this”关键字构造、使用原型prototype构造

    }  

11、window.onload和document ready的区别

window.onload 是在dom文书档案树加载完和具备文件加载完今后推行一个函数

document.ready原生中一向不这一个措施,jquery中有 $().ready(function),在dom文书档案树加载完今后推行五个函数(注意,那当中的文书档案树加载完不意味着任何文书加载完)。

$(document).ready要比window.onload先执行

window.onload只可以出去叁遍,$(document).ready能够出现每每

//编码成JScript字符串,不加两侧的引号
function String.prototype.EncodeJScript()
{
    var str=this;
    str=str.replace(/x5c/g,"\\");
    str=str.replace(/x2f/g,"\/");
    str=str.replace(/x3cS/g,"\u003cS");
    str=str.replace(/x3cs/g,"\u003cs");
    str=str.replace(/x22/g,"\"");
    str=str.replace(/x27/g,"\'");
    str=str.replace(/t/g,"\t");
    str=str.replace(/n/g,"\n");
    str=str.replace(/r/g,"\r");
    return str;
}function String.EncodeJScript(str){return String.Convert(str).EncodeJScript();}

<script>
window.onload=function(){
var iframe_arr=new window.frames[0].Array;
alert(iframe_arr instanceof Array); // false
alert(iframe_arr.constructor == Array); // false
}
</script>

Date对象

 

12、”==”和“===”的不同

前端会活动转变类型

后人不会

//保留换行,在服务器上解码会舍弃n
function String.prototype.EncodeJScriptCode()
{
    var str=this;
    str=str.replace(/x5c/g,"\\");
    str=str.replace(/x2f/g,"\/");
    str=str.replace(/x3cS/g,"\u003cS");
    str=str.replace(/x3cs/g,"\u003cs");
    str=str.replace(/x22/g,"\"");
    str=str.replace(/x27/g,"\'");
    str=str.replace(/t/g,"\t");
    str=str.replace(/n/g,"\n");
    str=str.replace(/r/g,"\r");
    return str;
}function String.EncodeJScriptCode(str){return String.Convert(str).EncodeJScriptCode();}

在Ajaxian上阅览了一种规范的检查测量检验方法,跨原型链调用toString()方法:Object.prototype.toString()。能够缓慢解决地方的跨框架难点。 当Object.prototype.toString(o)施行后,会施行以下步骤: 1)获取对象o的class属性。 2)连接字符串:"[object "+结果(1)+"]" 3)返回 结果(2) 例如:

TAG标签:
版权声明:本文由必威发布于必威-前端,转载请注明出处:迷失网络,数组1和数组2分别调用remove()方法