[转]JS学习总结-技巧、方法、细节 JS基础篇--JS按位非(~)运算符与~~运算符的理解分析

前端之家收集整理的这篇文章主要介绍了[转]JS学习总结-技巧、方法、细节 JS基础篇--JS按位非(~)运算符与~~运算符的理解分析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

变量转换@H_301_1@
var myVar  = "3.14159",str   = ""+ myVar,// string类型
int   = ~~myVar,1)">  number类型
float  = 1*myVar,1)"> number类型
bool  = !!myVar,1)"> boolean类型
array  = [myVar];  array类型

但是转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,创建正则表达式的时候要使用/pattern/flags这样的简化形式。

要了解~~运算符可以查看《JS基础篇--JS按位非(~)运算符与~~运算符的理解分析

取整同时转换成数值型 @H_301_1@
字符型变量参与运算时,JS会自动将其转换为数值型(如果无法转化,变为NaN)
'10.567890' | 0 10

JS里面的所有数值型都是双精度浮点数,
//因此,JS在进行位运算时,会首先将这些数字运算数转换为整数,然后再执行运算| 是二进制或, x|0 永远等于x;^为异或,同0异1,所以 x^0 还是永远等于x;~是按位取反,搞了两次以后值当然是一样的
'10.567890' ^ 0  结果: 10  

- 2.23456789 | 0 -2
~~2.23456789 2
~~-2.23456789 -2
~-2.23456789 1
~2.23456789 -3

日期转数值@H_301_1@
JS本身时间的内部表示形式就是Unix时间戳,以毫秒为单位记录着当前距离1970年1月1日0点的时间单位     
var d = +new Date(); 1488947616099

类数组对象转数组@H_301_1@
var arr =[].slice.call(arguments)

如下实例:

function test() {
  var res = ['a','b'];
  方法1
  res = res.concat([].slice.call(arguments,0));  0可省略,表示从开始位置截取
  
  方法2
  Array.prototype.push.apply(res,arguments); 
}
test('c','d');  ["a","b","c","d"]

进制之间的转换@H_301_1@
(int).toString(16);  converts int to hex,eg 12 => "C"
(int).toString(8);  converts int to octal,eg. 12 => "14"
parseInt(string,16)  converts hex to int,eg. "FF" => 255
parseInt(string,8)  converts octal to int,eg. "20" => 16

判断是否为IE@H_301_1@
edit http://www.lai18.com  貌似是最短的,利用IE不支持标准的ECMAscript中数组末逗号忽略的机制
var ie = !-[1 利用了IE的条件注释
var ie = /*@cc_on!@*/false;
 还是条件注释
var ie@cc_on=1; IE不支持垂直制表符
var ie = '\v'=='v' 原理同上
var ie = !+"\v1";

尽量利用原生方法@H_301_1@

要找一组数字中的最大数,我们可能会写一个循环,例如:

var numbers = [3,342,23,22,124];
var max = 0for(var i=0;i<numbers.length;i++){
 if(numbers[i] > max){
  max = numbers[i];
 }
}
alert(max);

其实利用原生的方法,可以更简单实现

];
numbers.sort(function(a,b){return b - a});
alert(numbers[0]);

当然最简洁的方法便是:

Math.max(12,123,3,2,433,4);  returns 433

当前也可以这样:

Math.max.apply(Math,[12,4]) 取最大值
Math.min.apply(Math,1)">取最小值

事件委派@H_301_1@

 举个简单的例子:HTML代码如下:

<h2>Great Web resources</>
ul id="resources">
 li><a href="http://opera.com/wsc">Opera Web Standards Curriculuma></="http://sitepoint.com">Sitepoint="http://alistapart.com">A List Apart="http://yuiblog.com">YUI Blog="http://blameitonthevoices.com">Blame it on the voices="http://oddlyspecific.com">Oddly specificul>

js代码如下:

 Classic event handling example
((){
 var resources = document.getElementById('resources');
 var links = resources.getElementsByTagName('a'var all = links.length;
 var i=0;i<all;i++){
   Attach a listener to each link
  links[i].addEventListener('click',handler,1)">);
 };
  handler(e){
  var x = e.target;  Get the link that was clicked
  alert(x);
  e.preventDefault();
 };
})();

利用事件委派可以写出更加优雅的:

();
 resources.addEventListener('click',1)"> get the link tha
  if(x.nodeName.toLowerCase() === 'a'){
   alert('Event delegation:' + x);
   e.preventDefault();
  }
 };
})();

你知道你的浏览器支持哪一个版本的Javascript吗?@H_301_1@
var JS_ver = [];
(Number.prototype.toFixed)?JS_ver.push("1.5"):;
([].indexOf && [].forEach)?JS_ver.push("1.6"):;
((function(){try {[a,b] = [0,1];return true;}catch(ex) {false;}})())?JS_ver.push("1.7"):;
([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):;
("".trimLeft)?JS_ver.push("1.8.1"):;
JS_ver.supports = ()
{
  if (arguments[0])
    return (!!~this.join().indexOf(arguments[0] +",") +",");
  else
    return (this[this.length-1]);
}
alert("Latest Javascript version supported: "+ JS_ver.supports());
alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));

判断属性是否存在@H_301_1@
 BAD: This will cause an error in code when foo is undefined
if (foo) {
  doSomething();
}
 GOOD: This doesn't cause any errors. However,even when foo is set to NULL or false,the condition validates as true
if (typeof foo != "undefined") {
  doSomething();
}
 BETTER: This doesn't cause any errors and in addition values NULL or false won't validate as true
 (window.foo) {
  doSomething();
}

有的情况下,我们有更深的结构和需要更合适的检查的时候:

 UGLY: we have to proof existence of every object before we can be sure property actually exists
if (window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
  doSomething();
}

其实最好的检测一个属性是否存在的方法为:

if("opera" in window){
  console.log("OPERA");
}else{
  console.log("NOT OPERA");
}

检测对象是否为数组@H_301_1@
var obj=[];
Object.prototype.toString.call(obj)=="[object Array]";

函数传递对象@H_301_1@
 doSomething() {
   Leaves the function if nothing is passed
  if (!arguments[0]) {
  ;
  }
  var oArgs  = arguments[0]
  arg0  = oArgs.arg0 || ""= oArgs.arg3 || [],  arg4  = oArgs.arg4 || ;
}
doSomething({
  arg1  : "foo"
});

循环中使用标签@H_301_1@

有时候循环当中嵌套循环,你可能想要退出某一层循环,之前总是用一个标志变量来判断,现在才知道有更好的方法

outerloop:
for (var iI=0;iI<5;iI++) {
   (somethingIsTrue()) {
   Breaks the outer loop iteration
  break outerloop;
  }
  innerloop:
  var iA=0;iA<5;iA++) {
     (somethingElseIsTrue()) {
     Breaks the inner loop iteration
     innerloop;
  }
  }
}  

转载地址:https://my.oschina.net/os2015/blog/465376

猜你在找的JavaScript相关文章