[轉]JS學習總結-技巧、方法、細節

變量轉換

var myVar  = "3.14159",
str   = ""+ myVar,// string類型
int   = ~~myVar, //  number類型
float  = 1*myVar, // number類型
bool  = !!myVar, // boolean類型
array  = [myVar]; // array類型

可是轉換日期(new Date(myVar))和正則表達式(new RegExp(myVar))必須使用構造函數,建立正則表達式的時候要使用/pattern/flags這樣的簡化形式。html

要了解~~運算符能夠查看《JS基礎篇--JS按位非(~)運算符與~~運算符的理解分析node

取整同時轉換成數值型 

//字符型變量參與運算時,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

日期轉數值

//JS自己時間的內部表示形式就是Unix時間戳,以毫秒爲單位記錄着當前距離1970年1月1日0點的時間單位     
var d = +new Date(); //1488947616099

類數組對象轉數組

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"]

進制之間的轉換

(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

//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";

儘可能利用原生方法

要找一組數字中的最大數,咱們可能會寫一個循環,例如:數組

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

其實利用原生的方法,能夠更簡單實現瀏覽器

var numbers = [3,342,23,22,124];
numbers.sort(function(a,b){return b - a});
alert(numbers[0]);

固然最簡潔的方法即是:app

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

當前也能夠這樣:函數

Math.max.apply(Math, [12, 123, 3, 2, 433, 4]) //取最大值
Math.min.apply(Math, [12, 123, 3, 2, 433, 4]) //取最小值

事件委派

 舉個簡單的例子:html代碼以下:oop

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

js代碼以下:post

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

利用事件委派能夠寫出更加優雅的:ui

(function(){
 var resources = document.getElementById('resources');
 resources.addEventListener('click',handler,false);
 function handler(e){
  var x = e.target; // get the link tha
  if(x.nodeName.toLowerCase() === 'a'){
   alert('Event delegation:' + x);
   e.preventDefault();
  }
 };
})();

你知道你的瀏覽器支持哪個版本的Javascript嗎?

var JS_ver = [];
(Number.prototype.toFixed)?JS_ver.push("1.5"):false;
([].indexOf && [].forEach)?JS_ver.push("1.6"):false;
((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;
([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;
("".trimLeft)?JS_ver.push("1.8.1"):false;
JS_ver.supports = function()
{
  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"));

判斷屬性是否存在

// 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
if (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");
}

檢測對象是否爲數組

var obj=[];
Object.prototype.toString.call(obj)=="[object Array]";

給函數傳遞對象

function doSomething() {
  // Leaves the function if nothing is passed
  if (!arguments[0]) {
  return false;
  }
  var oArgs  = arguments[0]
  arg0  = oArgs.arg0 || "",
  arg1  = oArgs.arg1 || "",
  arg2  = oArgs.arg2 || 0,
  arg3  = oArgs.arg3 || [],
  arg4  = oArgs.arg4 || false;
}
doSomething({
  arg1  : "foo",
  arg2  : 5,
  arg4  : false
});

循環中使用標籤

有時候循環當中嵌套循環,你可能想要退出某一層循環,以前老是用一個標誌變量來判斷,如今才知道有更好的方法:

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

轉載地址:https://my.oschina.net/os2015/blog/465376

相關文章
相關標籤/搜索