JavaScript 如何检查数组中是否存在字符串数据类型
在JavaScript中,数组是一组可以是相同类型或不同类型的数据。如果我们有包含数据的数组,我们的任务是确定它是否是字符串数据类型。在本文中,我们将学习如何使用 typeof 运算符。
语法:
typeof value
注意: typeof操作符返回一个表示操作数类型的字符串。
示例1:
输入:
const sample = “GeeksforGeeks”;
console.log(typeof sample);
输出: string
示例2:
输入:
const sample = 369;
console.log(typeof sample);
输出: number
示例3:
输入:
const sample = true;
console.log(typeof sample);
输出: boolean
方法:
- 遍历整个数组,检查每个元素是否为字符串,或者使用 for 循环进行检查。
- 使用 if 块将迭代器元素的类型与“string”数据类型进行比较。
- 如果遇到字符串数据类型,执行 if 块。
- 当没有字符串值时,执行 else 块。
示例1: 下面的代码演示了出现字符串的情况。
JavaScript
<script>
// Declare the array
const arr = [1,2,3,"Geeks",4];
// initialized flag to zero
let flag = 0;
// iterating over whole array element one by one
for(let i of arr){
// checking element is of type string or not
if(typeof i == 'string'){
console.log("String found");
flag = 1;
}
}
// if flag remain same that means we didn't get the string.
if(flag==0){
console.log("String not found");
}
</script>
输出:
String found
示例2: 下面的代码演示了字符串缺失的情况。
JavaScript
<script>
// Declare the array
const arr = [1,2,3,4,5];
// initialized flag to zero
let flag = 0;
// iterating over whole array element one by one
for(let i of arr){
// checking element is of type string or not
if(typeof i == 'string'){
console.log("String found");
flag = 1;
}
}
// if flag remain same that means we didn't get the string.
if(flag==0){
console.log("String not found");
}
</script>
输出:
String not found
我们可以使用 typeof 运算符来识别任何数据类型。我们可以将其用于其他数据类型,如数字、布尔值等。
方法2:使用 **Array.some()和 **instanceof :
- 初始化数组。
- 在数组上使用Some方法,它检查每个元素的实例并在任何字符串出现时返回true。
- 打印评估结果。
示例: 以下代码演示了字符串存在的情况。
Javascript
// Declare the array
const arr = [1, 2, "GFG", 4, 5];
// initialized flag to true if string found
let flag = arr.some(x => x instanceof String);
// if flag remain same that means we didn't get the string.
if (flag) {
console.log("String not found");
}
else {
console.log("String found")
}
输出结果:
String found
时间复杂度: O(N),N为数组的长度。
辅助空间复杂度: O(1),因为没有使用额外的空间。
极客教程