[英]Detecting template literals in javascript
We have two potential values: 我们有两个潜在价值:
const value = `Hello World`;
and 和
const value = {message: 'Hello World'};
What I'm trying to do is a conditional where 我想做的是有条件的
if(is template literal) {
// Some code
} else {
// Some code
}
I've tried using 我试过使用
if(String.raw(value)){
} else {
}
But the object throws a type error. 但是对象抛出类型错误。 Does anyone have an easy reliable way to detect template literals in javascript?
有没有人有一种简单可靠的方法来检测javascript中的模板文字?
Edit: Here is some further clarification for those who are asking. 编辑:这是对那些询问者的进一步说明。
const exampleFunc = (value) => {
// If I pass a string or template literal return as is
if (String.raw({raw: value})) return value;
const css = arr(styles).reduce((acc, obj) => {
// Passing an object handles a more complicated set of operations
}
}
Before I was using if (String.raw(value)) return value; 在我使用if(String.raw(value))返回值之前;
And what was happening here is it was giving me a type error rather than handing me null. 而且这里发生的是给我一个类型错误,而不是让我为空。 By passing {raw: value} to String.raw instead solved the problem and I can now detect whether its a string/template literal or an object.
通过将{raw:value}传递给String.raw可以解决问题,现在我可以检测出它是字符串/模板文字还是对象。
The clarifications to why I'm doing it this way is a longer story that has to do with React & styled components. 我为什么要这样做的澄清是一个更长的故事,与React和样式化组件有关。
There is no difference between using a string literal and a template literal (except, obviously, on the source code level). 使用字符串文字和模板文字之间没有区别(显然,在源代码级别上除外)。
But your first value
is a string, while the second one is an object, and those are easy to distinguish: 但是您的第一个
value
是一个字符串,而第二个值是一个对象,这些值很容易区分:
if (typeof value == "string") {
console.log(value)
} else if (typeof value == "object" && typeof value.message == "string") {
console.log(value.message)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.