DRA*_*RAX 1761
这对我有用:
if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else
Run Code Online (Sandbox Code Playgroud)
Pab*_*ruz 1505
你可以使用typeof
运营商:
var booleanValue = true;
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"
Run Code Online (Sandbox Code Playgroud)
此网页的示例.(虽然稍微修改了例子).
在使用创建的字符串的情况下,这将无法正常工作new String()
,但很少使用和推荐[1] [2].如果您愿意,请参阅其他答案,了解如何处理这些问题.
Orw*_*ile 136
由于580多人投票给出了不正确的答案,800多人投票赞成了一个有效但霰弹枪式的答案,我认为以一种每个人都能理解的简单形式重新回答我的答案是值得的.
function isString(x) {
return Object.prototype.toString.call(x) === "[object String]"
}
Run Code Online (Sandbox Code Playgroud)
或者,内联(我有一个UltiSnip设置):
Object.prototype.toString.call(myVar) === "[object String]"
Run Code Online (Sandbox Code Playgroud)
仅供参考,Pablo Santa Cruz的答案是错误的,因为typeof new String("string")
是object
DRAX的答案是准确和实用的,应该是正确答案(因为Pablo Santa Cruz绝对是错误的,我不会反对普遍的投票.)
但是,这个答案也绝对正确,实际上是最好的答案(可能除了建议使用lodash/underscore).免责声明:我为lodash 4代码库做出了贡献.
我的原始答案(显然直接飞过很多脑袋)如下:
我从underscore.js转码了这个:
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'].forEach(
function(name) {
window['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
Run Code Online (Sandbox Code Playgroud)
那将定义isString,isNumber等.
在Node.js中,这可以作为一个模块实现:
module.exports = [
'Arguments',
'Function',
'String',
'Number',
'Date',
'RegExp'
].reduce( (obj, name) => {
obj[ 'is' + name ] = x => toString.call(x) == '[object ' + name + ']';
return obj;
}, {});
Run Code Online (Sandbox Code Playgroud)
Cle*_*ud8 80
我建议使用jQuery或lodash/Underscore中的内置函数.它们使用起来更简单,更易于阅读.
这两个函数都将处理DRAX提到的情况......也就是说,它们都检查(A)变量是字符串文字还是(B)它是String对象的实例.在任何一种情况下,这些函数都正确地将值标识为字符串.
lodash/Underscore.js
if(_.isString(myVar))
//it's a string
else
//it's something else
Run Code Online (Sandbox Code Playgroud)
jQuery的
if($.type(myVar) === "string")
//it's a string
else
//it's something else
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅lodash文档了解_.isString().
有关详细信息,请参阅$ .type()的jQuery文档.
lin*_*ing 31
function isString (obj) {
return (Object.prototype.toString.call(obj) === '[object String]');
}
Run Code Online (Sandbox Code Playgroud)
我在这看到:
http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
Cod*_*ody 25
最好的办法:
var s = 'String';
var a = [1,2,3];
var o = {key: 'val'};
(s.constructor === String) && console.log('its a string');
(a.constructor === Array) && console.log('its an array');
(o.constructor === Object) && console.log('its an object');
(o.constructor === Number || s.constructor === Boolean) && console.log('this won\'t run');
Run Code Online (Sandbox Code Playgroud)
其中每一个都是由适当的类函数构造的,比如"new Object()"等.
此外,鸭子打字:"如果它看起来像一只鸭子,像鸭子一样走路,闻起来像一只鸭子 - 它必须是一个数组"意思,检查它的属性.
希望这可以帮助.
请记住,您也可以始终使用方法组合.以下是使用typeof的内联动作映射的示例:
var type = { 'number': Math.sqrt.bind(Math), ... }[ typeof datum ];
Run Code Online (Sandbox Code Playgroud)
这是使用内联映射的更"真实世界"示例:
function is(datum) {
var isnt = !{ null: true, undefined: true, '': true, false: false, 0: false }[ datum ];
return !isnt;
}
console.log( is(0), is(false), is(undefined), ... ); // >> true true false
Run Code Online (Sandbox Code Playgroud)
此函数将使用[custom]"type-casting" - 而不是"type - / - value-mapping" - 来确定变量是否实际"存在".现在你可以在null
&之间拆分那个讨厌的头发0
!
很多时候你甚至不关心它的类型.绕过打字的另一种方法是组合Duck-Type集:
this.id = "998"; // use a number or a string-equivalent
function get(id) {
if (!id || !id.toString) return;
if (id.toString() === this.id.toString()) http( id || +this.id );
// if (+id === +this.id) ...;
}
Run Code Online (Sandbox Code Playgroud)
两者Number.prototype
并 String.prototype
有.toString() method
.你只是确保数字的字符串等价物是相同的,然后你确保你把它http
作为一个传递给函数Number
.换句话说,我们甚至不关心它的类型.
希望能给你更多的工作:)
Kam*_*ski 22
今天 2020.09.17 我在 Chrome v85、Safari v13.1.2 和 Firefox v80 上针对选定的解决方案在 MacOs HighSierra 10.13.6 上执行测试。
对于所有浏览器(以及两个测试用例)
typeof||instanceof
(A, I) 和x===x+''
(H) 最快/最快_.isString
(lodash lib)是中/快更新:2020.11.28 我更新了x=123 Chrome
列的结果- 对于解决方案I
,之前可能存在错误值(= 69M 太低) - 我使用 Chrome 86.0 重复测试。
我为解决方案执行 2 个测试用例 A B C D E F G H I J K L
下面的片段显示了解决方案之间的差异
// https://stackoverflow.com/a/9436948/860099
function A(x) {
return (typeof x == 'string') || (x instanceof String)
}
// https://stackoverflow.com/a/17772086/860099
function B(x) {
return Object.prototype.toString.call(x) === "[object String]"
}
// https://stackoverflow.com/a/20958909/860099
function C(x) {
return _.isString(x);
}
// https://stackoverflow.com/a/20958909/860099
function D(x) {
return $.type(x) === "string";
}
// https://stackoverflow.com/a/16215800/860099
function E(x) {
return x?.constructor === String;
}
// https://stackoverflow.com/a/42493631/860099
function F(x){
return x?.charAt != null
}
// https://stackoverflow.com/a/57443488/860099
function G(x){
return String(x) === x
}
// https://stackoverflow.com/a/19057360/860099
function H(x){
return x === x + ''
}
// https://stackoverflow.com/a/4059166/860099
function I(x) {
return typeof x == 'string'
}
// https://stackoverflow.com/a/28722301/860099
function J(x){
return x === x?.toString()
}
// https://stackoverflow.com/a/58892465/860099
function K(x){
return x && typeof x.valueOf() === "string"
}
// https://stackoverflow.com/a/9436948/860099
function L(x) {
return x instanceof String
}
// ------------------
// PRESENTATION
// ------------------
console.log('Solutions results for different inputs \n\n');
console.log("'abc' Str '' ' ' '1' '0' 1 0 {} [] true false null undef");
let tests = [ 'abc', new String("abc"),'',' ','1','0',1,0,{},[],true,false,null,undefined];
[A,B,C,D,E,F,G,H,I,J,K,L].map(f=> {
console.log(
`${f.name} ` + tests.map(v=> (1*!!f(v)) ).join` `
)})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
This shippet only presents functions used in performance tests - it not perform tests itself!
Run Code Online (Sandbox Code Playgroud)
以下是 chrome 的示例结果
whe*_*ker 17
if (s && typeof s.valueOf() === "string") {
// s is a string
}
Run Code Online (Sandbox Code Playgroud)
适用于字符串文字let s = 'blah'
和对象字符串let s = new String('blah')
cus*_*der 14
我无法坦白地说为什么typeof
在这种情况下不能简单地使用它:
if (typeof str === 'string') {
return 42;
}
Run Code Online (Sandbox Code Playgroud)
是的,它将无法克服对象包装的字符串(例如new String('foo')
),但是这些被广泛认为是不好的做法,并且大多数现代开发工具都可能会阻止其使用。(如果看到一个,请修复它!)
该Object.prototype.toString
诀窍是什么,所有的前端开发人员已经被判有罪在自己的职业生涯有一天会做,但不要让它通过其巧妙抛光欺骗你:这会尽快打破的东西猴子补丁对象的原型:
if (typeof str === 'string') {
return 42;
}
Run Code Online (Sandbox Code Playgroud)
Sco*_*tyG 12
我喜欢使用这个简单的解决方案:
var myString = "test";
if(myString.constructor === String)
{
//It's a string
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*der 11
这是性能重要的一个很好的例子:
如果没有正确完成,做一些像字符串测试一样简单的事情可能会很昂贵.
例如,如果我想编写一个函数来测试某些东西是否为字符串,我可以通过以下两种方式之一来完成:
1) const isString = str => (Object.prototype.toString.call(str) === '[object String]');
2) const isString = str => ((typeof str === 'string') || (str instanceof String));
这两个都很直接,所以可能会影响性能?一般来说,函数调用可能很昂贵,特别是如果你不知道里面发生了什么.在第一个示例中,有一个对Object的toString方法的函数调用.在第二个示例中,没有函数调用,因为typeof和instanceof是运算符.运算符明显快于函数调用.
测试性能时,示例1比示例2慢79%!
请参阅测试:https://jsperf.com/isstringtype
我认为@customcommander 解决方案应该足以满足您 90% 的情况:
typeof str === 'string'
Run Code Online (Sandbox Code Playgroud)
应该为您服务(只是因为通常没有理由new String('something')
在您的代码中使用)。
如果您也有兴趣处理该String
对象(例如,您希望来自 3rd 方的一些 var),那么使用 lodash 作为@ClearCloud8 建议似乎是一个清晰、简单和优雅的解决方案。
但是,由于 lodash 的大小,我建议对诸如 lodash 之类的库保持谨慎。而不是做
import _ from 'lodash'
...
_.isString(myVar)
Run Code Online (Sandbox Code Playgroud)
这带来了整个巨大的 lodash 对象,我建议如下:
import { isString as _isString } from 'lodash'
...
_isString(myVar)
Run Code Online (Sandbox Code Playgroud)
通过简单的捆绑,你应该没问题(我在这里指的是客户端代码)。
一种简单快速的测试方法是使用构造函数名称属性。
let x = "abc";
console.log(x.constructor.name === "String"); // true
let y = new String('abc');
console.log(y.constructor.name === "String"); // true
Run Code Online (Sandbox Code Playgroud)
表现
取自lodash:
function isString(val) {
return typeof val === 'string' || ((!!val && typeof val === 'object') && Object.prototype.toString.call(val) === '[object String]');
}
console.log(isString('hello world!')); // true
console.log(isString(new String('hello world'))); // true
Run Code Online (Sandbox Code Playgroud)
你可以使用这个函数来确定任何东西的类型:
var type = function(obj) {
return Object.prototype.toString.apply(obj).replace(/\[object (.+)\]/i, '$1').toLowerCase();
};
Run Code Online (Sandbox Code Playgroud)
要检查变量是否为字符串:
type('my string') === 'string' //true
type(new String('my string')) === 'string' //true
type(`my string`) === 'string' //true
type(12345) === 'string' //false
type({}) === 'string' // false
Run Code Online (Sandbox Code Playgroud)
https://codepen.io/patodiblasi/pen/NQXPwY?editors=0012
要检查其他类型:
type(null) //null
type(undefined) //undefined
type([]) //array
type({}) //object
type(function() {}) //function
type(123) //number
type(new Number(123)) //number
type(/some_regex/) //regexp
type(Symbol("foo")) //symbol
Run Code Online (Sandbox Code Playgroud)
我也发现这也很好,而且比其他例子短得多.
if (myVar === myVar + '') {
//its string
} else {
//its something else
}
Run Code Online (Sandbox Code Playgroud)
通过连接空引号,它将值转换为字符串.如果myVar
已经是字符串,则if语句成功.
我发现这个简单的技术对字符串的类型检查很有用-
String(x) === x // true, if x is a string
// false in every other case
Run Code Online (Sandbox Code Playgroud)
String(x) === x // true, if x is a string
// false in every other case
Run Code Online (Sandbox Code Playgroud)
同样的技术也适用于Number -
Number(x) === x // true, if x is a number
// false in every other case
Run Code Online (Sandbox Code Playgroud)
const test = x =>
console.assert
( String(x) === x
, `not a string: ${x}`
)
test("some string")
test(123) // assertion failed
test(0) // assertion failed
test(/some regex/) // assertion failed
test([ 5, 6 ]) // assertion failed
test({ a: 1 }) // assertion failed
test(x => x + 1) // assertion failed
Run Code Online (Sandbox Code Playgroud)
对于正则表达式-
RegExp(x) === x // true, if x is a regexp
// false in every other case
Run Code Online (Sandbox Code Playgroud)
Number(x) === x // true, if x is a number
// false in every other case
Run Code Online (Sandbox Code Playgroud)
对象相同-
Object(x) === x // true, if x is an object
// false in every other case
Run Code Online (Sandbox Code Playgroud)
注意,正则表达式、数组和函数也被视为对象。
const test = x =>
console.assert
( Number(x) === x
, `not a number: ${x}`
)
test("some string") // assertion failed
test(123)
test(0)
test(/some regex/) // assertion failed
test([ 5, 6 ]) // assertion failed
test({ a: 1 }) // assertion failed
test(x => x + 1) // assertion failed
Run Code Online (Sandbox Code Playgroud)
但是,检查Array有点不同 -
Array.isArray(x) === x // true, if x is an array
// false in every other case
Run Code Online (Sandbox Code Playgroud)
RegExp(x) === x // true, if x is a regexp
// false in every other case
Run Code Online (Sandbox Code Playgroud)
这种技术并没有对工作职能然而-
Function(x) === x // always false
Run Code Online (Sandbox Code Playgroud)
如果您在node.js环境中工作,则可以在utils中使用内置函数isString.
const util = require('util');
if (util.isString(myVar)) {}
Run Code Online (Sandbox Code Playgroud)
编辑:正如@Jehy所提到的,自v4以来已弃用.
以下方法将检查任何变量是否为字符串(包括不存在的变量)。
const is_string = value => {
try {
return typeof value() === 'string';
} catch (error) {
return false;
}
};
let example = 'Hello, world!';
console.log(is_string(() => example)); // true
console.log(is_string(() => variable_doesnt_exist)); // false
Run Code Online (Sandbox Code Playgroud)