【问题标题】:How to remove the double quotes from array value which generates dynamically如何从动态生成的数组值中删除双引号
【发布时间】:2018-11-03 19:27:42
【问题描述】:

我在这里有一个简单的概念。单击控制台中的第一个按钮时,我会得到一些值,即增量索引++。我已经将值合并并放入第二个按钮的 onclick 数组中,现在输出为

["$('#chart1')", "$('#chart2')", "$('#chart3')"],

但我唯一需要解决的是删除数组中每个值周围的双引号。我需要这样的输出

[ $('#chart1'), $('#chart2'),$('#chart3')]

下面是代码。

html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div><button id="button1" class="button1">submit1</button> </div>
<div><button id="garray" class="button1">genarete-array</button> </div>

脚本

 var index = 0;
    var id = [];

    $('#button1').on('click', function() {
        index++;
        id.push(`$(\'#chart${index}\')`)
        console.log('chart' + index);
    });

$('#garray').on('click', function() {
console.log(id);
//output [ $('#chart1'), $('#chart2'),$('#chart3')]
})

【问题讨论】:

  • 你不能那样做。因为当你推送到数组时它会变成字符串
  • 你可以尝试添加数字/承诺/对象:var arr = []; arr.push(3);控制台.log(arr[0] === '3'); // 错误

标签: jquery html arrays


【解决方案1】:

你不能没有双引号来存储它,但你可以像下面那样替换它。

  var index = 0;
var id = [];

$('#button1').on('click', function() {
    index++;
    var temp="$('#chart"+index+"')";
    id.push(temp);
    console.log('chart' + index);
});

$('#garray').on('click', function() {

var string = JSON.stringify(id);
console.log(string.replace (/"/g,''));

//output [ $('#chart1'), $('#chart2'),$('#chart3')]
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div><button id="button1" class="button1">submit1</button> </div>
<div><button id="garray" class="button1">genarete-array</button> </div>

还有一件事是,如果您希望从字符串类型以外的其他类型中删除引号,您可以使用 map 函数。

stringvaribale.map(parseFloat), stringvaribale.map(Number),etc.

【讨论】:

    【解决方案2】:

    试试这个代码:

    id.push($(`#chart${index}`));
    

    你可以在这里测试它: https://jsfiddle.net/alonshmiel/x25btyn1/5/

    【讨论】:

      【解决方案3】:

      一旦你将它推送到一个数组中,根据你的数据它通常是字符串,所以对于这种情况,你应该将它转换为 JSON.stringify 然后尝试使用正则表达式 data.replace(/"/g,"") 来摆脱 cotes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-28
        • 1970-01-01
        • 1970-01-01
        • 2017-04-05
        相关资源
        最近更新 更多