blob: 24ce79a6e4f7fc6635640592d8ff696955f2414d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
---
title: 'TypeError: "x" is not a function'
slug: Web/JavaScript/Reference/Errors/Not_a_function
translation_of: Web/JavaScript/Reference/Errors/Not_a_function
---
<div>{{jsSidebar("Errors")}}</div>
<h2 id="訊息">訊息</h2>
<pre class="syntaxbox">TypeError: "x" is not a function
</pre>
<h2 id="錯誤類型">錯誤類型</h2>
<p>{{jsxref("TypeError")}}.</p>
<h2 id="哪裡錯了?">哪裡錯了?</h2>
<p>你想以函式呼叫一個數值,但該數值其實不是函式。程式碼期望你給出函式,但這份期望落空了。</p>
<p>也許打錯了函式的名字?也許呼叫的物件並沒有這個函式?例如說 JavaScript 物件並沒有 <code>map</code> 函式,但 JavaScript Array(陣列)物件則有。</p>
<p>許多內建函式都需要回呼(callback)的函式。為了讓下面的方法順利運作,你需要為它們提供函式:</p>
<ul>
<li>如果是 {{jsxref("Array")}} 或 {{jsxref("TypedArray")}} 物件:
<ul>
<li>{{jsxref("Array.prototype.every()")}}、{{jsxref("Array.prototype.some()")}}、{{jsxref("Array.prototype.forEach()")}}、{{jsxref("Array.prototype.map()")}}、{{jsxref("Array.prototype.filter()")}}、{{jsxref("Array.prototype.reduce()")}}、{{jsxref("Array.prototype.reduceRight()")}}、{{jsxref("Array.prototype.find()")}}</li>
</ul>
</li>
<li>如果是 {{jsxref("Map")}} 與 {{jsxref("Set")}} 物件:
<ul>
<li>{{jsxref("Map.prototype.forEach()")}} 與 {{jsxref("Set.prototype.forEach()")}}</li>
</ul>
</li>
</ul>
<h2 id="實例">實例</h2>
<h3 id="函式的名字打錯了">函式的名字打錯了</h3>
<p>這種事太常發生了。下例就有個方法打錯:</p>
<pre class="brush: js example-bad">var x = document.getElementByID("foo");
// TypeError: document.getElementByID is not a function
</pre>
<p>該函式的正確名字為 <code>getElementByI<strong>d</strong></code>:</p>
<pre class="brush: js example-good">var x = document.getElementById("foo");
</pre>
<h3 id="函式呼叫到錯誤的物件">函式呼叫到錯誤的物件</h3>
<p>某些方法需要你提供回呼的函式,該函式只能作用於特定物件。以本例而言,我們使用的 {{jsxref("Array.prototype.map()")}} 就只能作用於 {{jsxref("Array")}} 物件。</p>
<pre class="brush: js example-bad">var obj = { a: 13, b: 37, c: 42 };
obj.map(function(num) {
return num * 2;
});
// TypeError: obj.map is not a function</pre>
<p>請改用陣列:</p>
<pre class="brush: js example-good">var numbers = [1, 4, 9];
numbers.map(function(num) {
return num * 2;
});
// Array [ 2, 8, 18 ]
</pre>
<h2 id="參見">參見</h2>
<ul>
<li><a href="/zh-TW/docs/Web/JavaScript/Reference/Functions">Functions</a></li>
</ul>
|