JS总结篇--[转]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如许的简化情势。

取整同时转换成数值型 

//字符型变量介入运算时,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]);

固然最简约的要领就是:

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代码以下:

<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代码以下:

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

应用事宜委派能够写出越发文雅的:

(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…

    原文作者:风雨后见彩虹
    原文地址: https://segmentfault.com/a/1190000008612497
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞