`

CHAPTER 3 Types, Values, and Variables

 
阅读更多
3.1 Numbers

不像很多的语言,javaScript不区分integer类型和浮点类型。所有的数字都用浮点类型。Javascript用64bit浮点类型来表示。

十六进制:
0xff // 15*16 + 15 = 255 (base 10)
八进制:
0377 // 3*64 + 7*8 + 7 = 255 (base 10)

数字的表示方法:
[digits][.digits][(E|e)[(+|-)]digits]
例如:
3.14
2345.789
.333333333333333333
6.02e23 // 6.02 × 10^23
1.4738223E-32 // 1.4738223 × 10^−32

infinity:

var zero = 0; // Regular zero
var negz = -0; // Negative zero
zero === negz // => true: zero and negative zero are equal
1/zero === 1/negz // => false: infinity and -infinity are not equal

3.1.5 Dates and Times
var then = new Date(2010, 0, 1); // The 1st day of the 1st month of 2010
var later = new Date(2010, 0, 1, // Same day, at 5:10:30pm, local time
17, 10, 30);
var now = new Date(); // The current date and time
var elapsed = now - then; // Date subtraction: interval in milliseconds
later.getFullYear() // => 2010
later.getMonth() // => 0: zero-based months
later.getDate() // => 1: one-based days
later.getDay() // => 5: day of week. 0 is Sunday 5 is Friday.
later.getHours() // => 17: 5pm, local time
later.getUTCHours() // hours in UTC time; depends on timezone
later.toString() // => "Fri Jan 01 2010 17:10:30 GMT-0800 (PST)"
later.toUTCString() // => "Sat, 02 Jan 2010 01:10:30 GMT"
later.toLocaleDateString() // => "01/01/2010"
later.toLocaleTimeString() // => "05:10:30 PM"
later.toISOString() // => "2010-01-02T01:10:30.000Z"; ES5 only


3.2 Text

3.2.4 Pattern Matching
var text = "testing: 1, 2, 3"; // Sample text
var pattern = /\d+/g // Matches all instances of one or more digits
pattern.test(text) // => true: a match exists
text.search(pattern) // => 9: position of first match
text.match(pattern) // => ["1", "2", "3"]: array of all matches
text.replace(pattern, "#"); // => "testing: #, #, #"
text.split(/\D+/); // => ["","1","2","3"]: split on non-digits


3.3 Boolean Values

默认代表false的:
undefined
null
0
-0
NaN
"" // the empty string

如果有下面的语句:
if (o !== null) ...
直接可以写成
if(o).....

3.4 null and undefined

我们经常使用null来表示一个变量没有值,null也是一个对象,这个对象代表"no object"

我们同样可以使用undefined来表示一个变量没有值,但是它是一个更深层次上的,它表示一个变量没有被初始化,或者这个变量根本就不存在在这个对象当中,同样可以表示一个方法没有返回值。

如果你使用typeof来操作undefined,它会返回undefined。

null和undefined都表示没有赋值,使用==来比较它们会返回true,使用严格的===可以区分出来它们。

你或许想使用undefined来表示系统级的异常,null来表示编程级别的异常,如果你想将它们变成参数传递给方法,那么这个方法最后使用null来做参数。

3.5 The Global Object

var global = this; // Define a global variable to refer to the global object

3.6 Wrapper Objects

Javascript对象是由许多值组成的,它们是名值对。

String不是对象,但是,为什么它可以使用属性呢?当我们引用String的时候,Javascript将String的值变成一个对象,就如:new String(s),对象继承了string的函数和属性引用。当属性被引用完毕的时候,对象将会被销毁。number和boolean是一个道理。看下面的代码:

var s = "test"; // Start with a string value.
s.len = 4; // Set a property on it.
var t = s.len; // Now query the property.


首先给变量s赋值为test,然后调用s.len,这时会创建一个String对象,将len的值设置为4,然后String对象被销毁。第三行代码,将s.len的值赋值给变量t,因为刚才的对象被销毁了,所以这个值是undefined。因为这次创建的String对象没有len这个属性。

==操作符对待变量和它的包装类一样,如果想区分它们可以使用===,typeof同样可以区分原始变量和类。

3.7 Immutable Primitive Values and Mutable Object References

我们无法改变原始类型,即使像改变一个数字的值。String也是同样,当我们改变String的值,其实原来的String还是原来的样子。

var s = "hello"; // Start with some lowercase text
s.toUpperCase(); // Returns "HELLO", but doesn't alter s
s // => "hello": the original string has not changed

原始类型比较相不相等,主要看它的值,如果值相同那么它们就是相同的,String比较的是String的长度,和每个位置的字符是否相等。

而Object是可变的,即使它们属性的值相等也不能算相等。数组也是同样,即使含有相同的元素。

Object我们有时候叫它们为引用类型,两个Object相等,只有它们的引用指向了同一个Object。

var a = []; // The variable a refers to an empty array.
var b = a; // Now b refers to the same array.
b[0] = 1; // Mutate the array referred to by variable b.
a[0] // => 1: the change is also visible through variable a.
a === b // => true: a and b refer to the same object, so they are equal.


3.8 Type Conversions

10 + " objects" // => "10 objects". Number 10 converts to a string
"7" * "4" // => 28: both strings convert to numbers
var n = 1 - "x"; // => NaN: string "x" can't convert to a number
n + " objects" // => "NaN objects": NaN converts to string "NaN"

3.8.1 Conversions and Equality

因为Javascript能自由的转化变量,它的==操作符也同样是灵活的。下面的都是true,例如:
null == undefined // These two values are treated as equal.
"0" == 0 // String converts to a number before comparing.
0 == false // Boolean converts to number before comparing.
"0" == false // Both operands convert to numbers before comparing.


===操作符不会先进行转化。

3.8.3 Object to Primitive Conversions

Object_to_boolean 返回的都是true 即使是new Boolean("false"),同样返回true

将一个object转换成String

1. 如果有toString函数,那么调用toString函数。
2. 如果没有toString函数,那么去找valueOf函数,如果返回一个原始类型,再将这个原始类型转换成String返回。
3. 如果这俩都没有,那么报typeError异常。

将一个object转换成数字:

与上面的过程差不多,只不过先调用valueOf函数。

例子:空的数组返回0,只有一个元素的数组返回这个数字。如果这个数组为空,那么valueOf返回Object,然后调用toString方法,返回空字符,然后空字符转化成0.如果只有一个数字,那么返回这个字符,然后转换成这个数字。

var now = new Date(); // Create a Date object
typeof (now + 1) // => "string": + converts dates to strings
typeof (now - 1) // => "number": - uses object-to-number conversion
now == now.toString() // => true: implicit and explicit string conversions
now > (now -1) // => true: > converts a Date to a number

3.9 Variable Declaration

javascript的函数范围意味着所有在函数内部的变量声明是在整个函数体都可见的。变量是可见的即使在声明之前。

var scope = "global";
function f() {
console.log(scope); // Prints "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined everywhere
console.log(scope); // Prints "local"
}


你可能会想第一行的代码应该打印global,因为local变量还没有被执行,但是因为函数范围规则,这种情况没有发生。本地变量在整个函数体范围内被定义,表示global变量被隐藏了。尽管local变量被定义了,但是它没有被初始化知道被执行。

3.10.3 The Scope Chain

当一个函数被定义,它保存了将要生效的范围链。当函数被调用,它创建一个新的object来保存贝蒂变量,添加一个新的object到保存范围链中,创建一个新的,长久的链,它代表函数的调用范围。每次外部函数调用的时候,内部函数都会被定义一次,由于范围链在每次调用的时候都不同,内部函数在定义的时候都会不一样,内部函数的代码是一样的,但是范围链却不一样。

这个范围链的概念对于理解声明和closures非常有帮助。
分享到:
评论

相关推荐

    JavaScript权威指南(第6版)

    Chapter 3 Types, Values, and Variables Chapter 4 Expressions and Operators Chapter 5 Statements Chapter 6 Objects Chapter 7 Arrays Chapter 8 Functions Chapter 9 Classes and Modules Chapter 10 Pattern ...

    JavaScript权威指南(第6版).JavaScript:The.Definitive.Guide

    Chapter 3 Types, Values, and Variables Chapter 4 Expressions and Operators Chapter 5 Statements Chapter 6 Objects Chapter 7 Arrays Chapter 8 Functions Chapter 9 Classes and Modules Chapter 10 Pattern ...

    Learning.Scala.Practical.Functional.Programming.for.the.JVM

    Learn about the core data types, literals, values, and variables Discover how to think and write in expressions, the foundation for Scala's syntax Write higher-order functions that accept or return ...

    C 程序设计教学课件:Chapter 3 class and object.ppt

    Chapter 3 of the C++ programming course delves into the fundamental concepts of object-oriented programming, specifically focusing on classes and objects. Object-oriented programming (OOP) is a ...

    Learn.Cplusplus.In.A.DAY.1519318588.epub

    Chapter 3: Variables and Data Types Chapter 4: Operators Chapter 5: Advanced Data Types Chapter 6: Loops and Conditional Statements Chapter 7: Arrays and Pointers Chapter 8: Functions Chapter 9: ...

    Getting-Started-with-Julia-Programming

    Chapter 2, Variables, Types, and Operations, discusses the elementary built-in types in Julia, and the operations that can be performed on them, so that you are prepared to start writing the code with...

    The.Dart.Programming.Language.03219277

    Dart’s object model, in which everything is an object, even numbers and Boolean values How Dart programs are organized into modular libraries How Dart functions are structured, stored in variables, ...

    c-programming-for-scientists-and-engineers-manufacturing-engineering-series

    The chapter begins with an overview of the fundamental concepts of variables and data types in C programming. It introduces the basic syntax and semantics of declaring and initializing variables. ###...

    Think Julia

    Learn about values, variables, statements, functions, and data structures in a logical progression Discover how to work with files and databases Understand types, methods, and multiple dispatch ...

    Java2核心技术卷I+卷2:基础知识(第8版) 代码

    Chapter 3: Fundamental Programming Structures in Java 35 A Simple Java Program 36 Comments 39 Data Types 40 Variables 44 Operators 46 Strings 53 Input and Output 63 Control Flow 71 Big ...

    Addison.Wesley.The.Java.Programming.Language.4th.Edition.Aug.2005.chm

    Chapter 7Tokens, Values, and Variablesdescribes the tokens of the language from which statements are constructed, the types defined by the language and their allowed values, and the variables that ...

    Problem Solving with C++ (7th edition)

    - **Return Types and Values**: Discussion of return types and values, including void functions that do not return a value. **Programming Project 4.7**: This project likely involves writing and using ...

    Professional C# 3rd Edition

    Chapter 3: Objects and Types 83 Classes and Structs 84 Class Members 85 Data Members 85 Function Members 85 xi Contents readonly Fields 99 Structs 101 Structs Are Value Types 102 Structs and ...

    SCJP6 Sun Certificated Programmer for Java 6 Study Guide (Exam 310-065) 英文原版

    - **Variable Declarations**: This section covers the basics of declaring variables, including primitive types and object references. - **Access Modifiers**: Understanding how to use `public`, `...

    Beginning PHP 5.3

    - **Variables and Data Types:** Introduction to PHP variables and data types (strings, integers, arrays, etc.). - **Simple Operations:** Basic arithmetic and string manipulation examples using PHP. #...

    Microsoft Visual C# 2013 Step by Step,最新资料

    CHAPTER 9 Creating value types with enumerations and structures 207 CHAPTER 10 Using arrays 227 CHAPTER 11 Understanding parameter arrays 251 CHAPTER 12 Working with inheritance 263 CHAPTER 13 ...

    Addison.Wesley.C++.by.Dissection.2002.pdf

    Chapter 2 delves deeper into the native types and statements used in C++: - **Program Elements:** Covers comments, keywords, identifiers, literals, operators, and punctuators. - **Input/Output:** ...

Global site tag (gtag.js) - Google Analytics