本文共 3490 字,大约阅读时间需要 11 分钟。
本文将围绕JavaScript中的20个常见问题展开,详细解答每个问题,并通过实际代码示例帮助开发者理解和掌握相关知识。
问题描述:
尽管typeof bar === "object"
是检查 bar
是否为对象的可靠方法,但 null
也被认为是对象。这会导致许多开发者陷入困境。 解决方案:
为了避免这种情况,可以结合null
检查,确保 bar
不是 null
。同时,考虑到函数和数组的情况,可以进一步优化如下: console.log((bar !== null) && (typeof bar === "object" || typeof bar === "function"));
注意事项:
toString.call(bar) !== "[object Array]"
。代码:
(function() { var a = b = 3;})();console.log("a defined? " + (typeof a !== 'undefined'));console.log("b defined? " + (typeof b !== 'undefined'));
输出结果:
a defined? false
b defined? true
原因分析:
var a = b = 3;
实际上等价于 b = 3; var a = b;
,因此 a
是全局变量,b
是封闭函数的局部变量。严格模式下的解决方案:
在严格模式下,这种语法会抛出ReferenceError: b is not defined
,强制遵守变量声明规则。 代码:
var myObject = { foo: "bar", func: function() { var self = this; console.log("outer func: this.foo = " + this.foo); console.log("outer func: self.foo = " + self.foo); (function() { console.log("inner func: this.foo = " + this.foo); console.log("inner func: self.foo = " + self.foo); }()); }};myObject.func();
输出结果:
原因分析:
func
中的 this
和 self
都指向 myObject
。this
在现代 JavaScript 中指向 window
对象,但在严格模式下为 undefined
。封装意义:
示例:
(function($) { // jQuery 插件代码 $(document).ready(function() { // 使用 $ 符号引用 jQuery });})(jQuery);
意义:
this
和错误抛出。示例:
在代码开头加入:"use strict";
代码:
function foo1() { return { bar: "hello" };}function foo2() { return { bar: "hello" };}
输出结果:
foo1()
输出: {bar: "hello"}
。foo2()
输出: undefined
。原因分析:
foo1()
中的 return
后有分号,导致后续代码被忽略。foo2()
中的 return
后缺少分号,导致后续代码被执行。定义:
NaN
表示非数字值,是不可转换的数值。 检测方法:
Number.isNaN()
更可靠。function isNaN(num) { return typeof num === "number" && Number.isNaN(num);}
代码:
console.log(0.1 + 0.2);console.log(0.1 + 0.2 == 0.3);
输出结果:
0.1 + 0.2
可能输出 0.30000000000000004
。0.1 + 0.2 == 0.3
输出 false
。原因分析:
函数实现:
function isInteger(x) { return (x ^ 0) === x;}
解释:
x ^ 0
将 x
转换为整数。代码:
(function() { console.log(1); setTimeout(function() { console.log(2); }, 1000); setTimeout(function() { console.log(3); }, 0); console.log(4);})();
输出结果:
原因分析:
setTimeout
0ms后立即插入事件队列,console.log(3)
会在 console.log(4)
之前执行。函数实现:
function isPalindrome(str) { str = str.replace(/\W/g, '').toLowerCase(); return str === str.split('').reverse().join('');}
示例:
isPalindrome("level")
返回 true
。isPalindrome("levels")
返回 false
。实现方法:
function sum(x) { if (arguments.length == 2) { return x + arguments[1]; } else { return function(y) { return x + y; }; }}
另一种方法:
function sum(x, y) { if (y !== undefined) { return x + y; } else { return function(y) { return x + y; }; }}
问题描述:
无论用户点击哪个按钮,i
值都会显示为 5
。 解决方案:
for (var i = 0; i < 5; i++) { (function(x) { setTimeout(function() { console.log(x); }, x * 1000); })(i);}
通过以上问题解答与示例,开发者可以更深入地理解JavaScript的核心概念,提升代码编写和调试能力。
转载地址:http://lzgfk.baihongyu.com/