变量的函数参数作为字符串javascript失败

时间:2018-06-03 16:27:37

标签: javascript

本作品:

setTheme('#222','#000','wheat','red','wheat','none','none');

这不起作用,,

var theme01 = "'#222','#000','wheat','red','wheat','none','none'"; <br>
setTheme(theme01);

console.log(theme01) = '#222','#000','wheat','red','wheat','none','none'

所以转换为字符串会以某种方式混淆它?

在捕获画布之前,我将切换各种主题?我把它全部用在了CSS上,但是canvas没有捕获css更改或css注入。所以我现在已经准备好使用Vanilla Javascript了,但是在经过数小时的测试搜索之后需要帮助才能将变量传递给我的函数。

function setTheme(topp, bott, txt, hlin, vlin, fOrb, sOrb) {
  var xx = document.querySelectorAll(".hlin");
  for (var i = 0; i < xx.length; i++) {
    xx[i].style.stroke = hlin;
  }
  var xx = document.querySelectorAll(".vlin");
  for (var i = 0; i < xx.length; i++) {
    xx[i].style.stroke = vlin;
  }
  var xx = document.querySelectorAll(".txt");
  for (var i = 0; i < xx.length; i++) {
    xx[i].style.fill = txt;
  }
  document.getElementById("svg_20").style.fill = topp;
  document.getElementById("svg_1").style.fill = bott;
  document.getElementById("svg_2").style.fill = bott;
  document.getElementById("svg_3").style.stroke = txt;
  document.getElementById("svg_5").style.stroke = txt;
  document.getElementById("svg_21").style.fill = fOrb;
  document.getElementById("svg_21").style.stroke = sOrb;
};

3 个答案:

答案 0 :(得分:1)

是的,您不能为逗号分隔的字符串交换参数列表。您应该使用数据结构来存储它们,如数组或对象。这是一个如何使用对象的示例。

var theme01 = { topp: '#222', bott: '#000', txt: 'wheat' };
function setTheme ( options ) {
    document.getElementById("svg_20").style.fill = options.topp;
    document.getElementById("svg_1").style.fill = options.bott;
    document.getElementById("svg_3").style.fill = options.txt;
}
setTheme( theme01 )

答案 1 :(得分:0)

该字符串将是您的函数的一个参数。您可以将Function.apply)1与分割字符串一起用作第二个参数,甚至更简单,使用spread运算符2)。演示:

1)Function.apply

2)spread operator

&#13;
&#13;
( () => {
  const log = str => document.querySelector("#result").textContent += `${str} \n`;
  const parameterString = "#222,#000,wheat";
  // no dice
  log("someFn(parameterString) => no dice"); 
  someFn(parameterString);
  
  // use apply
  log("\nsomeFn.apply(null, parameterString.split(\",\")) => ah yes, that works");
  someFn.apply(null, parameterString.split(","));
  
  // or use spread operator
  log("\nsomeFn(...parameterString.split(\",\")) => ah yes, that works too");
  someFn(...parameterString.split(","));
  
  function someFn(p1, p2, p3) {
    log(p1);
    log(p2);
    log(p3);
  }
  
})();
&#13;
<pre id="result"></pre>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用spread syntax将其作为数组传递,但不能传递一串项目并将它们作为多个参数。

function setTheme(topp, bott, txt, hlin, vlin, fOrb, sOrb) {
  console.log(topp)
  console.log(bott)
  console.log(txt)
  console.log(hlin)
  console.log(vlin)
  console.log(fOrb)
  console.log(sOrb)
}

let items = ['#222', '#000', 'wheat', 'red', 'wheat', 'none', 'none']


setTheme(...items)