简体   繁体   English

如何在JavaScript中的字符串上调用函数?

[英]How to invoke a function on a String in javascript?

Maybe this is weird, but I have one more question for the same GA API helper function. 也许这很奇怪,但是对于相同的GA API帮助程序功能,我还有另一个问题。 I need strings which will specify filter conditions, but I don't know how to use it properly. 我需要指定过滤条件的字符串,但是我不知道如何正确使用它。 Basically I want to generate and return a string such as "ga:medium==organic" from this function call medium.equals(organic) where var organic = "organic" and var medium = "ga:medium" . 基本上,我想从此函数调用medium.equals(organic)生成并返回一个字符串,例如"ga:medium==organic" ,其中var organic = "organic"var medium = "ga:medium" I know how to work with the two strings to produce the output, and there are a lot more conditions to code for, but I just need to know how to invoke the function on the string medium and then how to use both the invoking object (string) and the arguments to return an output. 我知道如何使用两个字符串来产生输出,还有很多要编写的条件,但是我只需要知道如何在字符串medium上调用函数,然后如何同时使用调用对象(字符串)和返回输出的参数。 Is what I'm asking possible? 我要问的可能吗?

You can add methods to the string object and then refer to this to access the string you're operating on. 您可以将方法添加到字符串对象,然后引用this对象以访问您正在操作的字符串。

String.prototype.equals = function(arg) {
    return this + "==" + arg;
}

var medium = "ga:medium";
var organic = "organic";
var output = medium.equals(organic);   // "ga:medium==organic"

Working demo: http://jsfiddle.net/jfriend00/hNLy6/ 工作演示: http : //jsfiddle.net/jfriend00/hNLy6/

If your question is to compare two string logically and not as objects: 如果您的问题是在逻辑上比较两个字符串而不是作为对象:

You can make use of the "===" operator which compares two operands for logical equality as well as the type of the operands. 您可以使用“ ===”运算符,该运算符比较两个操作数的逻辑相等性以及操作数的类型。

Example: 例:

var x="5"; var x =“ 5”;

x==="5" // returns true x ===“ 5” //返回true

x===5 // returns false x === 5 //返回false

Refer to this: http://www.w3schools.com/js/js_comparisons.asp 引用此: http : //www.w3schools.com/js/js_comparisons.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM