如何在JavaScript中仅打印包含不同数据类型的数组中的字符串

zphenhs4  于 2023-01-04  发布在  Java
关注(0)|答案(4)|浏览(76)

我有:

const fruits = ["Banana", "Orange", "Apple", "Mango", 9];
let text = fruits.toString();
console.log(text)

它打印了整个数组,但我只想打印数组中的字符串元素,不包括9,我该怎么做呢?
结果-香蕉,橙子,苹果,芒果,9
所需结果-香蕉、橙子、苹果、芒果

new9mtju

new9mtju1#

使用数组filtertypeof获取结果

const fruits = ["Banana", "Orange", "Apple", "Mango", 9];

let text = fruits.filter(r => typeof(r) === "string");

console.log(text)
mu0hgdu0

mu0hgdu02#

const fruits = ["Banana", "Orange", "Apple", "Mango",9];
let text = fruits.filter(f => typeof (f) === 'string').toString();
console.log(text)

typeof运算符可用于确定每个对象的数据类型。
filter可用于只过滤掉那些满足给定条件或 predicate 的元素。

bpsygsoo

bpsygsoo3#

const fruits = ["Banana", "Orange", "Apple", "Mango", 9]
.filter(text => typeof(text) === "string").toString();
    
    console.log(fruits)
kkbh8khc

kkbh8khc4#

只需过滤类型为字符串(使用typeof运算符)的项(使用filter函数)。

const fruits = ["Banana", "Orange", "Apple", "Mango",9];
// filter the string data type items
let text = fruits.filter(item => typeof item === "string").toString();
console.log(text)

相关问题