为什么我的 return 数组函数在 returnig 到数组的值后不会使用或结合 "Math" 方法?

Why my return array function won't using or combinning with "Math" methode after it has returnig to the array's values?

猜猜...我正在尝试编写一个函数,该函数 return 是一个数组,我可以将其传递为字符串格式。就像我要在这里提到的:我有 randomColor(customColorsArrays, takenColorsArray) 该函数取决于 class 已填充 如果两者都为空return颜色的值已经通过数学方法计算,如果customColorsArrays的class已经被用户填充到把他们自己的数组主题, 如果 class 两者都由用户编写意味着 return 数组的 var 已经设置在一个更早的里面功能。为了清楚地看到这些代码的下方:


function randomColor(customColorsArray, takenColorsArray) {
 var text = "",
     colors = ["orange", "yellow", "red", "maroon"];

   if (customColorsArray && takenColorsArray) {
      var text = "["+colors+"]";
   }
     else if (!customColorsArray && !takenColorsArray) {
      text += colors[Math.floor(Math.random() * colors.length)];
   }
     else {
      text += customColorsArray[Math.floor(Math.random() * customColorsArray.length)];
  };

   return text;
}

function personalRandomColor(e) {
 var text = "";

   if (e == "orange") {text += "almond";}
    else if (e == "yellow") {text += "melrose";}
    else if (e == "red") {text += "danube";}
    else if (e == "maroon") {text += "magenta";};

  return text;
}


这是实现上述功能的HTML代码。

bla... bla... bla...
  var customColorsArrays = randomColor('passingClass', 'takenColor'),
      randomFirstColor = randomColor(),
      skipFirstColors = customColorsArrays.replace('\[', '\[\"').replace('\]', '\"\]').replace(/[\,]/g, '\"\, \"').replace('\"'+randomColor()+'\"\,', ''),
      randomSecondColor = personalRandomColor(randomColor(toString(skipFirstColors))),
bla... bla... bla...

修复代码的一种简单直接的方法是替换行

randomSecondColor = personalRandomColor(randomColor(toString(skipFirstColors)))

对于

randomSecondColor = personalRandomColor(randomColor(JSON.parse(skipFirstColors)))

这样做的原因是 randomColor 采用元素数组,而您要将一个字符串传递给它。参数 skipFirstColors 是一个字符串,它实际上是字符串列表的 JSON 表示。您希望它是一个实际列表,而不是表示列表的字符串。

JSON.parse 函数将评估由 skipFirstColors 编辑的字符串 return 和 return 它代表的列表。

此外,我建议您重新审视并可能重构您的代码。您应该尝试使用内置类型,例如列表作为函数 returns 而不是使用对象的 JSON 表示(序列化为字符串),因为这样可以避免此类错误,并且使代码更简洁。