`
iwebcode
  • 浏览: 2013899 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

(OTHER)JavaScript初学者的10个迷你技巧

 
阅读更多

1,在一个数组的最后添加一个元素

这个技巧可以让你使用Length属性在一个数组的最后添加一个元素,因为Length属性比数组的最后一个元素的下标多1。这个方法和“push”方法是相同的。例如:

var myArray = [];  
myArray[myArray.length] = 'New Element';  

2,调整一个数组的长度

Length属性不是只读的,所以你可以设置Length属性的值。而且,你可以使用它增大或缩小数组的长度。例如:

var myArray = [1,2,3];  
myArray.length // 3  
myArray.length = 2; //Delete the last element  
myArray.length = 20 // add 18 elements to the array; the elements have the undefined value. 

3,使用“!!”把任意数据类型转换成Boolean

这个技术可以让你使用“!!”把任意数据类型(比如string, number或integer)转换成Boolean。例如:

var myString = '23255';  
typeof myString; //String     
myString = !!myString;  
typeof myString  //Boolean 

4,把Number转换成String

这个技巧可以让你在number的结尾添加一个空的string来把number转换成string,例如:

var mynumber = 234;  
typeof mynumber; //Number     
mynumber += '';  
typeof mynumber; //String 

5,了解一个函数需要多少个变量

这是一个伟大的技巧,可以让你准确地知道一个函数需要多少个变量。例如:

function add_nums(num1, num2){       
    return num1 + num2;  
}  
add_nums.length // 2 is the amount of parameters expected by the function add_nums 

6,使用“arguments”对象来了解一个函数接收到了多少个参数

这个技术可以让你使用“arguments”对象来了解一个函数接收到了多少个参数。例如:

function add_nums(){      
    return arguments.length;  
}     
add_nums(23,11,32,56,89,89,89,44,6); //this return the number 9 

当你需要检查参数个数的有效性的时候,或者当你需要创建一个不确定参数个数的函数的时候,这个技巧是很有用的。

function sum_three_nums( ){   
    if(arguments.length!=3) 
        throw new Error('received ' + arguments.length + ' parameters and should work with 3');     
}     
sum_three_nums(23,43); //Return the error message     
function sum_num(){      
    var total = 0;      
    for(var i=0;i<arguments .length;i++){          
    total+=arguments[i];      
    }      
    return total;  
}     
sum_num(2,34,45,56,56); 

7,把对象当成参数,来组织和改善函数

在现代Web开发中,对象最普遍的一个用途是把它们当成函数的参数。要记住函数参数的这个规则总是很困难的;但是,使用一个对象是十分有好处的,因为我们不必再担心参数的规则了。而且,它更有组织性,可以让用户更好的理解我们要做什么。这个方法可以让你把对象当成参数,来组织和改善函数。例如:

function insertData(name,lastName,phone,address){      
    code here;  
} 

重构以后的代码是这样的:


function insertData(parameters){        
    var name = parameters.name;      
    var lastName = parameters.lastName;      
    var phone = parameters.phone;      
    var address = parameters.address;  
} 

当你要使用默认值的时候,它也是十分有用的。例如:

function insertData(parameters){        
    var name = parameters.name;      
    var lastName = parameters.lastName;      
    var phone = parameters.phone;      
    var address = parameters.address;      
    var status = parameters.status || 'single' //If status is not defined as a property 
//in the object the variable status take single as value  } 

现在,要使用这个函数十分的简单;我们可以用两种方式来发送数据:



//Example 1  
insertData({
    name:’Mike’, 
    lastName:’Rogers’, 
    phone:’555-555-5555’,
    address:’the address’, 
    status:’married’
});        
//Example 2  
var myData = {       
    name:’Mike’,                            
    lastName:’Rogers’,                                  
    phone:’555-555-5555’,                               
    address:’the address’,                                   
    status:’married’                         
};     
insertData(myData); 

8,函数就是数据

函数就是像strings或numbers那样的数据,我们可以把它们当成函数参数来传递它们,这可以创建十分令人惊讶而又“威风凛凛”的Web应用程序。这个方法是非常有用的,几乎所有的主流框架都使用了这个方法。例如:

function byId(element, event, f){      
    Document.getElementById(element).['on'+event] = f; //f is the function that we pass as parameter  
}     
byId('myBtn','click',function(){
    alert('Hello World')
});     
Another example of functions as data:     
//Example 1  
function msg(m){      
    Alert(m);  
}     
//Example 2  
var msg = function(m){ alert(m);} 

这些函数几乎是完全相同的。唯一的区别是使用它们的方式。例如:第一个函数,在你声明它以前,你就可以使用它了;但是第二个函数只有声明以后才能使用:

//Example 1  
msg('Hello world'); //This will work     
function msg(m){      alert(m);  }     
//Example 2  
msg('Hello world'); //Does not work because JavaScript cannot find the function msg because is used before is been declared.     
var msg = function(m){ alert(m)} 

9,扩展本地对象

虽然一些JavaScript的领袖不推荐这个技术,但是它已经被一些框架使用了。它可以让你针对JavaScript API来创建一些辅助性的方法。

//We create the method prototype for our arrays  
//It only sums numeric elements     
Array.prototype.sum = function(){       
    var len = this.length;      
    total = 0;      
    for(var i=0;i<len ;i++){          
        if(typeof this[i]!= 'number') continue;           
        total += this[i];      
    }      
    return total;  
}     
var myArray = [1,2,3,'hola'];  
myArray.sum();              
Array.prototype.max = function(){       
    return Math.max.apply('',this);  
}    

10,Boolean

注意它们之间的区别,因为这会节省你调试脚本的时间。

'' == '0'          // false  
0 == ''            // true  
0 == '0'           // true  
false == 'false'   // false  
false == '0'       // true  
false == undefined // false  
false == null      // false  
null == undefined  // true  
true == 1          // true  
'' == null         // false  
false == ''        // true 

如果你在其他地方看过这些脚本,那么这些技巧可以帮助你融会贯通。这些技巧甚至还不及JavaScript所有功能的冰山一角,但是这是一个开始!请不要客气,留下你的评论,问题,额外的技巧或疑虑吧,但是请记住,这是一篇针对初学者的文章!!我希望能收到一些开发者同行的来信!Enjoy!

分享到:
评论

相关推荐

    Beginning.JavaScript.5th.Edition

    Chapter 17: Other Javascript Libraries Chapter 18: Common Mistakes, Debugging, And Error Handling Appendix A: Answers To Exercises Appendix B: Javascript Core Reference Appendix C: W3C Dom Reference ...

    Speaking JavaScript

    Background: Understand JavaScript’s history and its relationship with other programming languages. Tips, tools, and libraries: Survey existing style guides, best practices, advanced techniques, ...

    JavaScript Functional Programming for JavaScript Developers (PDF, EPUB, MOBI)

    The [removed] Functional Programming for JavaScript Developers course will take you on a journey to show how functional programming when combined with other techniques makes JavaScript programming ...

    JavaScript Patterns

    and other language-specific categories, the abstractions and code templates in this guide are ideal -- whether you're writing a client-side, server-side, or desktop application with JavaScript....

    javascript面向对象编程指南 2nd

    javascript面向对象编程指南 2nd英文版,英文名:Object-Oriented JavaScript。 What you will learn from this book The basics of object-oriented programming, and how to apply it in the JavaScript ...

    JavaScript: Moving to ES2015

    JavaScript: Moving to ES2015 by Ved Antani English | 24 Mar. 2017 | ASIN: B06XWDKLS8 | 1194 Pages | AZW3 | 9.08 MB Explore and master modern JavaScript techniques with ES2015 in order to build large-...

    Test-Driven JavaScript Development

    If you’re an experienced programmer with no prior experience with JavaScript, this part should help you understand where JavaScript differs from other languages, especially less dynamic ones, and ...

    【JavaScript源代码】React 小技巧教你如何摆脱hooks依赖烦恼.docx

    React 小技巧教你如何摆脱hooks依赖烦恼  react项目中,很常见的一个场景: const [watchValue, setWatchValue] = useState(''); const [otherValue1, setOtherValue1] = useState(''); const [otherValue2, ...

    The Principles of Object-Oriented JavaScript 1st Edition

    Zakas thoroughly explores JavaScript's object-oriented nature, revealing the language's unique implementation of inheritance and other key characteristics. You'll learn: –The difference between ...

    Enhancing Adobe Acrobat DC Forms with JavaScript

    • Utilize complex forms that include drop down and list boxes in combination with other form fields • Work with Action Wizard and JavaScript • Improve form navigation and printing of forms • Add ...

    Javascript.Object.Oriented.Programming.pdf

    Using JavaScript, you can create interactive web pages along with desktop widgets, browser, and application extensions, and other pieces of software. Object-oriented programming, which is popularly ...

    Learning JavaScript Design Patterns - Addy Osmani.pdf

    This book also walks experienced JavaScript developers through modern module formats, how to namespace code effectively, and other essential topics. Learn the structure of design patterns and how ...

    JavaScript Domain-Driven Design(PACKT,2015)

    JavaScript backs some of the most advanced applications. It is time to adapt modern software development practices from JavaScript to model complex business needs. JavaScript Domain-Driven Design ...

    Advanced.Game.Design.with.HTML5.and.JavaScript.1430258004

    All the techniques covered in this book are core game design skills that can be applied to many other programming technologies. Table of Contents Chapter 1. Level-up: New JavaScript Tricks Chapter 2...

    JavaScript: The Good Parts

    If you want to learn more about the bad parts and how to use them badly, consult any other JavaScript book., JavaScript is the language of the Web -- the only language found in all browsers -- so ...

    Packt.Object-Oriented.JavaScript.3rd.Edition

    oriented programming in the JavaScript environment Use a JavaScript Console with complete mastery Make your programs cleaner, faster, and compatible with other programs and libraries Get familiar with...

    other 和another的区别

    other和others 1. other作形容词或代词,通常用在复数名词的前面,意为“别的;其他的;另外的”。 例如: I'll come again some other day. 我改日再来。 other前有冠词the即可与单数名词连用。 如:John did ...

Global site tag (gtag.js) - Google Analytics