模拟shell';回声&x27;使用JavaScript实现函数
我想构建一个模拟shell命令行为的函数:模拟shell';回声&x27;使用JavaScript实现函数,javascript,parsing,variables,echo,this,Javascript,Parsing,Variables,Echo,This,我想构建一个模拟shell命令行为的函数:echo“var:$var” 代码的草稿可能是: // Scratch of a shell like 'echo' function echo(t){ var m= t.match(/\$[A-Za-z0-9]+/g); m.unique().forEach(function(entry) { var re=new RegExp ("\\" + entry, "g"); t=t.replace(re, this[entr
echo“var:$var”
代码的草稿可能是:
// Scratch of a shell like 'echo'
function echo(t){
var m= t.match(/\$[A-Za-z0-9]+/g);
m.unique().forEach(function(entry) {
var re=new RegExp ("\\" + entry, "g");
t=t.replace(re, this[entry.substr(1)]);
});
console.log(t);
}
其中unique()
对数组进行操作,顾名思义:
// Helper function: make array unique
Array.prototype.unique =function () {
return this.filter(function(elem, pos) {
return this.indexOf(elem) == pos;
}, this);
};
使用全局对象时,一切正常:
//Global objects
var var1="value1";
s="var1 has $var1";
echo(s);
给出:
"var1 has value1"
正如所料。不幸的是,在函数中:
//Global and local objects
function foo(){
var var2="value2";
s2="var2 has $var2";
echo(s);
echo(s2);
}
foo();
。。。只能捕获函数变量名称:
"var1 has value1"
"var2 has undefined"
鉴于var1
存储在this
中,一个简单的解决方案可能是将var2
也存储在那里:
function foo(){
this.var2="value2";
s2="var2 has $var2";
echo(s);
echo(s2);
}
foo();
给予:
"var1 has value1"
"var2 has value2"
除了重写变量声明的成本之外,将所有内容存储为全局变量似乎是一个非常糟糕的主意。传递到echo
所涉及的单个变量数组将在printf
中对其进行转换(已实现)。传递一个{var1:“value1”,…}
序列比echo
保存的时间要长
你有什么更好的主意/诀窍吗?正如@adeneo所说,这没有多大意义 与其强迫一种语言像另一种语言那样工作,不如适应它的语法 那么,你可以使用
function echo() {
console.log(Array.prototype.slice.call(arguments, 0).join(''));
}
就这样说吧
var var1 = "value1";
echo("var1 has ", var1); // "var1 has value1"
或者直接使用
var var1 = "value1";
console.log("var1 has " + var1); // "var1 has value1"
这真的没什么意义?为什么您需要在一种不真正支持它的语言中使用字符串中的变量,而不将变量传递给函数,您就无能为力,正如您现在使用
this[entry.substr(1)]
所做的那样,您处于全局范围,而this
是窗口,这就是为什么它只适用于附加到窗口的变量。