JS和jquery的几个令人迷惑的问题之一-类型、值、变量、运算符和表达式

本文深入讲解JavaScript的基础知识,包括变量作用域、类型转换、特殊数值处理、字符串编码、布尔值及算术运算等内容,帮助读者掌握JS编程的核心要点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

node

可以验证js的语法


1.jquery的$

selector选择器

特殊用法:

$(function(){

}

相对于js里面的document.onload(){

}

$('#test1')
相当于
document.getElementById("test1")


2.JS的函数

http://www.jb51.net/article/37044.htm

function语句 vs.构造函数 vs.函数直接量

1.function functionName(arg0, arg1, ... argN) { statements }//function语句
2.var function_name = new Function(arg1, arg2, ..., argN, function_body);//Function()构造函数
3.var func = function(arg0, arg1, ... argN) { statements };//函数直接量
1.function f(x){return x*x};//function语句
2.var f = new Function("x","return x*x;");//Function()构造函数
3.var f = function(x){return x*x;};//函数直接量 

1.function functionName(arg0, arg1, ... argN) { statements }//function语句
2.var function_name = new Function(arg1, arg2, ..., argN, function_body);//Function()构造函数
3.var func = function(arg0, arg1, ... argN) { statements };//函数直接量

3.jquery 的each函数

http://www.jb51.net/article/46014.htm

4.js不区分整数值和浮点数值

js中的数字全部用浮点数值表示

浮点数值类似于C++/Java中的双精度类型

整数的范围因为精度的关系比浮点数窄的多 308vs.53

需要注意的是,js中实际的操作一般使用32位整数,如数组索引,位操作符


5.js的类型转换

很自由,需要字符串的时候提供了数字会自动转换。这一点和python很不同,对于多语言程序员来说必须注意。

尽量使用===而不要使用==

===比==更加严格

==在判断两个值是否相等的时候做了类型转换;而===从来不做类型转换

复杂之处在于,就算转换以后都一样,但也不见得就==的。

> undefined==false  //if语句将undefined转换为false,但是==拒绝转换操作数为布尔值
false
> 0==false
true

> null==undefined
true
> "0"==false
true
> "0"==0
true


当然这里面还有一些比较微妙的东西,待细细体会以后再总结

6.js语言的类型

分为原始类型和对象类型

原始类型包括数字 字符串和布尔类型

两个特殊的原始值null和undefined。

对象类型是属性的集合,每个属性都由名值对组成,名值对里面的值可以是各种类型也可以是对象类型的值。

有一个特殊的对象是全局对象,global object

另外一个特殊对象是array(数组)

特殊对象还有函数

类是对象类型的子类型,他是有函数来定义的(构造函数)。

   js核心定义了几种类:Date,RegExp,Error

js面向对象的特性:

  技术上说,只有对象类型有方法,但是原始类型也有方法,只有null和undefined没有方法。

7.js语言的变量

变量是untyped,可以初始化为任何类型的值,也可以随时改变为其他类型的值。

7.1.变量的作用域

js采用词法作用域

变量有两种作用域

   全局变量(全局作用域)

   局部变量(函数作用域)


var scope = "global scope"; // A global variable
function checkscope() {
    var scope = "local scope"; // A local variable
    function nested() {
      var scope = "nested scope"; // A nested scope of local variables
      return scope; // Return the value in scope here
    }
    return nested();
}
checkscope() // => "nested scope"

和C语言的块级作用域不一样,JS在函数中定义的局部变量,在声明他的函数内以及这个函数体嵌套的任意函数体内都是有定义的。

function test(o) {
  var i = 0; // i is defined throughout function
  if (typeof o == "object") {
    var j = 0; // j is defined everywhere, not just block
    for(var k=0; k < 10; k++) { // k is defined everywhere, not just loop
      console.log(k); // print numbers 0 through 9
    }
    console.log(k); // k is still defined: prints 10
  }
  console.log(j); // j is defined, but may not be initialized
}
函数提前声明的特殊现象

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

等价于下面的代码:

function f() {
  var scope; // Local variable is declared at the top of the function
  console.log(scope); // It exists here, but still has "undefined" value
  scope = "local"; // Now we initialize it and give it a value
  console.log(scope); // And here it has the value we expect
}

由于js没有块级作用域,所以程序员一个最佳实践是把局部变量放在函数体顶部,这样源代码就非常清晰反映了真实的变量作用域。

7.2.作为属性的变量

使用var声明的全局变量是不能被删除的,而直接赋值产生的全局变量却可以被删除。

var truevar = 1; // A properly declared global variable, nondeletable. 这个属性是不可配置的
fakevar = 2; // Creates a deletable property of the global object.  全局对象的正常的可配置的属性
this.fakevar2 = 3; // This does the same thing.
delete truevar // => false: variable not deleted
delete fakevar // => true: variable deleted 
delete this.fakevar2 // => true: variable deleted

7.3.作用域链 scope chain

对于理解with语句是非常有帮助的,同样对于理解闭包的概念也至关重要。


8.算术运算

除了+-*/ %这些操作符以外,

还可以使用Math对象的属性定义的函数和常量来实现。

算术运算的特殊之处,溢出和下溢或者被0整除的时候不会报错。

没有溢出overflow,有Infinity和-Infinity表示正负无穷大。

没有下溢underflow(无穷接近于0的时候),js将会返回0.负数下溢返回负0

被0整除一般返回无穷大或者负无穷大,0/0返回NaN,表示Not a Number

9.特殊的全局变量Infinity,NaN

还有Number对象

//Infinity无穷大

Infinity // A read/write variable initialized to Infinity.
Number.POSITIVE_INFINITY // Same value, read-only.
1/0 // This is also the same value.

Number.MAX_VALUE + 1 // This also evaluates to Infinity.

//负无穷大

Number.NEGATIVE_INFINITY // These expressions are negative infinity.
-Infinity
-1/0

-Number.MAX_VALUE - 1

//NaN

NaN // A read/write variable initialized to NaN.
Number.NaN // A read-only property holding the same value.

0/0 // Evaluates to NaN.

//负零

Number.MIN_VALUE/2 // Underflow: evaluates to 0
-Number.MIN_VALUE/2 // Negative zero
-1/Infinity // Also negative 0
-0  //负零

10.几个特殊算术运算

js中的非数字值比较特殊,和任何值都不相等,包括自身。

10.1.isNaN(x) 判断是否NaN

等价于

x!=x

如果参数x是NaN或者是一个非数字值,返回true

10.2.isFinite() 判断是否有限数字

NaN,Infinity和 -Infinity返回False,其他值返回true

10.3.0和-0是相等的

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

11.字符集 内码(codepoint) 和js字符串

js采用了utf-16编码的utf字符集

代理项对

  所以如果某个字符的内码是17位的,就只能用2个utf-16(16位值)来表示。

也就是说就算某个js字符串长度为2,也可能是只是表示了一个unicode字符而已。

需要注意,js的字符串操作不能够识别这个情况。

均作用于16位值,而不是字符,而且不会对代理项对做单独处理。


12.布尔值

true

false

任何javascript的值都可以转换成bool值

下面的值会被转化成false

falsy value

undefined
null
0
-0
NaN
"" // the empty string

所有其他值(truthy value),包括对象都会被转换成true


13.null 和undefined

通常认为null和undefined分别是他们自有类型的唯一成员

typeof(null);//object,js的关键字

typeof(undefined)//undefined,是预定义的全局变量,而不是js的关键字

null==undefined;//true

null===undefined;//false


14.global object(全局对象)

浏览器环境或者nodejs环境启动以后,都会产生一个全局对象,并给他一组定义的初始属性集合:全局属性,全局函数,构造函数(定义了js的类),其他全局对象

• global properties like undefined, Infinity, and NaN
• global functions like isNaN(), parseInt() (§3.8.2), and eval() (§4.12).
• constructor functions like Date(), RegExp(), String(), Object(), and Array()
(§3.8.2)
• global objects like Math and JSON (§6.9)


虽然他们不是保留字,但是他们应该被当做保留字来对待。

客户端js来说,windows对象定义了额外的全局属性


在代码的最顶级,可以使用关键字this来引用这个全局对象。


在客户端js中,Window对象充当了全局对象

Window对象有一个属性window引用其自身,可以替代this使用


如果代码定义了全局变量,这些全局变量就是全局对象的属性


15.包装对象

String,Boolean,Number

使得原始类型看起来有了方法。(通过创建一个临时包装对象来实现)


16.类型的显式转换

> NaN.toString()
'NaN'
> typeof(NaN)
'number'
> Number("3") // => 3
3
> String(false) // => "false" Or use false.toString()
'false'
> Boolean([]) // => true
true
> Object(3) // => new Number(3)
{}
> Object(null)
{}

> var x=55
undefined
> x+""
'55'
> x
55
> y=x+""
'55'
> y
'55'
> +y
55
> y
'55'
> z=+y
55
> z
55
> a=!!z
true
> z
55
> a
true
>

//字符串转换为数字

> parseInt("077")
77
> parseInt("077",8)
63
> parseInt("0x77")
119
>

17.表达式和左值

左值是个古老的词汇

是指表达式能够出现在赋值语句左侧。

在js中,变量、对象属性、数组元素均是左值。规范允许built-in function返回左值,但是自定义函数不能。

18.算术表达式和运算次序

> a=1
1
> b=(a++)+a
3
假设c=a++

c=1,a=2

b=1+2=3


19.算术表达式和操作符

5/2=2.5

注意js是浮点数表示所有的数字。区别于java的5/2=2

1/0=Infinity

-1/0=-Infinity

0/0=NaN

%求模

> 175%3
1
> 175%13
6
> -175%13  //求模或者余数,结果的符号和第一个操作数的符号保持一致
-6

位操作符<<,>>,>>>
> 7>>1   
3
> -7>>1   //带符号右移
-4
> -7>>>1   //无符号右移
2147483644
> -1>>>1
2147483647
> -1>>>4
268435455
> -1>>4
-1
> 1<<4    //左移
16
> -1<<4
-16
>


20.关系表达式

20.1. ==和===

== 

!=

===

!==

> 0==-0
true
> 0===-0
true
> NaN!=NaN
true
> null!=null
false
> null==null
true
> undefined==undef
true
> a=null
null
> var a=null
undefined
> var b=null
undefined
> a==b
true
> var cc,dd;
undefined
> cc==dd
true
> typeof(cc)
'undefined'
> typeof(dd)
'undefined'
> typeof(a)
'object'
> cc===dd
true
> a===b
true
> NaN!==NaN
true
> a===cc
false
> a==cc
true
> "1"==true
true
> "1"===true
false
>

20.2.比较运算符

>

<

>=

<=

字符串比较使用String.localeCompare(),更加健壮

因为不同语言中的字符次序可能会不一样。

另外,注意一般来说,大写字母比小写字母小。

有时候,需要使用String.toUpperCase()这种方法来转换字符串的大小写以后再比较。


加号操作符和比较操作符在转换操作数的偏好上面有所不同,加号操作符更加偏向于转换为字符串,而比较操作符偏向于转换为数字再比较。

1 + 2 // Addition. Result is 3.
"1" + "2" // Concatenation. Result is "12".
"1" + 2 // Concatenation. 2 is converted to "2". Result is "12".
11 < 3 // Numeric comparison. Result is false.
"11" < "3" // String comparison. Result is true.
"11" < 3 // Numeric comparison. "11" converted to 11. Result is false.
"one" < 3 // Numeric comparison. "one" converted to NaN. Result is false.

20.3.in操作符

> var point = { x:1, y:1 }; // Define an object
undefined
> "x" in point // => true: object has property named "x"
true
> "z" in point // => false: object has no "z" property.
false
> "toString" in point // => true: object inherits toString method
true
> var data = [7,8,9]; // An array with elements 0, 1, and 2
undefined
> "0" in data // => true: array has an element "0"
true
> 1 in data // => true: numbers are converted to strings
true
> 3 in data // => false: no element 3
false
> 7 in data;
false

20.4.instanceof操作符

这个需要理解prototype chain原型链

o instanceof f

对象o存在一个隐藏的成员,这个成员指向其父类的原型,如果父类的原型是另外一个类的实例的话,则这个原型对象里面也存在一个隐藏成员指向另外一个类的原型,这就是原型链。


21.逻辑表达式

21.1.&&

var o = { x : 1 };
var p = null;
o && o.x // => 1: o is truthy, so return value of o.x
p && p.x // => null: p is falsy, so return it and don't evaluate p.x  不再计算右边的那部分

&&有时候称为短路(short circuiting)

if (a == b) stop(); // Invoke stop() only if a == b
(a == b) && stop(); // This does the same thing

所以要注意右操作数里面的带有副作用的部分,这部分有可能不会被执行。你要了解这一情况。


21.2.||

// If max_width is defined, use that. Otherwise look for a value in
// the preferences object. If that is not defined use a hard-coded constant.
var max = max_width || preferences.max_width || 500;
This idiom is often used in function bodies to supply default values for parameters:
// Copy the properties of o to p, and return p
function copy(o, p) {
  p = p || {}; // If no object passed for p, use a newly created object.
  // function body goes here
}

22.=赋值表达式

> var a=1
undefined
> a
1
> var b=2
undefined
> b
2
> (a=b)==0
false
> (a=b)==2
true
>
23.表达式计算 evel和gevel

var geval = eval; // Using another name does a global eval
var x = "global", y = "global"; // Two global variables
function f() { // This function does a local eval
  var x = "local"; // Define a local variable
  eval("x += 'changed';"); // Direct eval sets local variable
  return x; // Return changed local variable
}
function g() { // This function does a global eval
  var y = "local"; // A local variable
  geval("y += 'changed';"); // Indirect eval sets global variable 
  return y; // Return unchanged local variable
}
console.log(f(), x); // Local variable changed: prints "localchanged global":
console.log(g(), y); // Global variable changed: prints "local globalchanged":

24.其他运算符

24.1.?:

24.2.typeof

x                               typeof x
undefined                     "undefined"
null                          "object"
true or false                 "boolean"
any number or NaN             "number"
any string                    "string"
any function                  "function"
any nonfunction native object "object"
any host object                An implementation-defined string, but not “undefined”, “boolean”, “number”, or “string”.
function vs. callable object的微妙区别?看糊涂了

24.3.delete

> var o = { x: 1, y: 2}; // Start with an object
undefined
> delete o.x; // Delete one of its properties
true
> "x" in o // => false: the property does not exist anymore
false
> var a = [1,2,3]; // Start with an array
undefined
> delete a[2]; // Delete the last element of the array
true
> a.length // => 2: array only has two elements now
3
> var o = {x:1, y:2}; // Define a variable; initialize it to an object
undefined
> delete o.x; // Delete one of the object properties; returns true
true
> typeof o.x; // Property does not exist; returns "undefined"
'undefined'
> delete o.x; // Delete a nonexistent property; returns true
true
> delete o; // Can't delete a declared variable; returns false.
false
> // Would raise an exception in strict mode.
undefined
> delete 1; // Argument is not an lvalue: returns true
true
> this.x = 1; // Define a property of the a global object without var
1
> delete x; // Try to delete it: returns true in non-strict mode
false
> x
1
> delete this.x;
false
> x
1
> this.x
1

24.4.void

<a href="javascript:void window.open();">Open New Window</a>

24.5.逗号操作符,

通常在for循环里面使用

> // The first comma below is part of the syntax of the var statement
undefined
> // The second comma is the comma operator: it lets us squeeze 2
undefined
> // expressions (i++ and j--) into a statement (the for loop) that expects 1.
undefined
> for(var i=0,j=10; i < j; i++,j--)// 第一个逗号是变量声明语句的一部分,第二个逗号才是操作符
... console.log(i+j);
10
10
10
10
10
undefined
>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值