【问题标题】:Issue on Loading String of Numbers to Array of Numbers将数字字符串加载到数字数组的问题
【发布时间】:2017-06-23 17:06:53
【问题描述】:

我在将点击框的背景颜色加载到 rgb 数组时遇到问题。

当我使用 rgb1 = color.split(","); 这个创建字符串数组时,你可以看到

[
  "49",
  " 133",
  " 155"
]

所以我尝试将项目解析为 int,例如 rgb2 = parseInt(color.split(","));,但现在我在返回时得到了 49

请告诉我如何将结果导出为

[49、133、155]

 $(".box").on("click", function () {

  color = $(this).css("background-color").substring(4).slice(0,-1);

  rgb1 = color.split(",");
  rgb2 = parseInt(color.split(","));
  
  console.log(color);
  console.log(rgb1);
  console.log(rgb2);
  
});
.box{
    height:30px;
    width:30px;
    background:#31859B;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>

【问题讨论】:

标签: javascript


【解决方案1】:

您可以使用仅匹配数字部分的正则表达式。然后将字符串转换为数字。

var color = "49, 133, 155",
    parts = color.match(/\d+/g).map(Number);

console.log(parts);

【讨论】:

    【解决方案2】:

    $(".box").on("click", function () {
    
      color = $(this).css("background-color").substring(4).slice(0,-1);
    
      rgb1 = color.split(",");
      rgb2 = [];
    
      for (var i = 0; i < rgb1.length; i++) {
        rgb2[i] = parseInt(rgb1[i]);
      }
      console.log(rgb2);
      
    });
    .box{
        height:30px;
        width:30px;
        background:#31859B;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="box"></div>

    【讨论】:

      猜你喜欢
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 2014-10-24
      • 2013-04-15
      • 2017-01-31
      相关资源
      最近更新 更多