TypeError: join 不是 JavaScript 中的函数
TypeError: join is not a function in JavaScript
“TypeError: join is not a function” 当我们join()
在一个不是数组的值上调用方法时发生。
要解决该错误,请确保仅join
在有效数组上调用该方法。
下面是错误如何发生的示例。
const arr = {}; // ⛔️ Uncaught TypeError: join is not a function const result = arr.join(',');
我们
在一个对象上调用了Array.join()方法并返回了错误。
Array.join()
只在数组上调用方法
要解决该错误,console.log
您调用该join
方法的值并确保它是一个有效的数组。
const arr = ['bobby', 'hadz', 'com']; const result = arr.join(','); // 👇️ "bobby,hadz,com" console.log(result);
在调用之前检查该值是否为数组join()
您可以使用Array.isArray
方法有条件地检查值是否为数组
。
const arr = null; const result = Array.isArray(arr) ? arr.join(',') : ""; console.log(result); // 👉️ ""
if/else
我们使用了三元运算符,它与语句非常相似。
如果值是一个数组,我们返回调用该join
方法的结果。否则,我们返回一个空字符串。
这样,即使值不是数组,您也不会收到错误。
您还可以使用简单的if
语句来检查值是否为数组。
const arr = null; let result = ''; if (Array.isArray(arr)) { result = arr.join(','); } console.log(result); // 👉️ ""
如果arr
变量存储一个数组,if
块将在我们调用
join()
方法的地方运行。
在调用之前将值转换为数组join()
If you have an array-like object, use the Array.from()
method to convert it to
an array before calling join()
.
const set = new Set(['bobby', 'hadz', 'com']); const result = Array.from(set).join(','); console.log(result); // 👉️ "bobby,hadz,com"
We used the Array.from()
method to convert a Set
object to an array to be
able to use the Array.join()
method.
You could achieve the same result by using the spread syntax (…).
const set = new Set(['one', 'two', 'three']); const result = [...set].join(','); console.log(result); // 👉️ "one,two,three"
If you have an object that has an array property, access the property before
calling the join()
method.
const obj = { site: ['bobby', 'hadz', 'com'], }; const result = obj.site.join(', '); console.log(result); // 👉️ bobby, hadz, com
We accessed a property on the object that stores an array to be able to call the
join()
method.
If the value is fetched from a remote server, make sure it is of the type you
expect it to be by logging it to the console.
Also, ensure you have parsed it to a native JavaScript array before calling the
join
method on it.
The
Array.join()
method concatenates all of the elements in an array using a separator.
The only argument the Array.join()
method takes is a separator
– the string
used to separate the elements of the array.
If a value for the separator
argument is omitted, the array elements are
joined with a comma ,
.
If the separator
argument is set to an empty string, the array elements are
joined without any characters in between them.
Conclusion #
The “TypeError: join is not a function” occurs when we call the join()
method on a value that is not an array. To solve the error, make sure to only
call the join
method on valid arrays.