如何使用JavaScript在单个变量中添加多个值?

时间:2019-02-06 10:44:53

标签: javascript jquery

如何在单个变量中获得多个值,如下所示:

1, 2, 3, 4, 5

$('.icon').click(function() {
  var totalWishlist;
  $(this).toggleClass('active');
  totalWishlist += $(this).attr('data-pid');
  console.log(totalWishlist);          
});
.active{color:red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="icon" data-pid="1">icon 1</div>
<div class="icon" data-pid="2">icon 2</div>
<div class="icon" data-pid="3">icon 3</div>
<div class="icon" data-pid="4">icon 4</div>

我为什么得到undefined

3 个答案:

答案 0 :(得分:2)

您将得到undefined1等,因为您没有使用值声明totalWishlist,因此默认情况下它是未定义的。要解决此问题,请将其定义为点击处理程序外部的空字符串:

var totalWishlist = '';

但是,使用数组和push()会更有意义。这很容易修改。如果要从该数组中检索字符串,可以使用join(', '),如下所示:

var totalWishlist = [];

$('.icon').click(function() {
  totalWishlist.push($(this).data('pid'));
  console.log(totalWishlist.join(', '));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="icon" data-pid="1">icon 1</div>
<div class="icon" data-pid="2">icon 2</div>
<div class="icon" data-pid="3">icon 3</div>
<div class="icon" data-pid="4">icon 4</div>

答案 1 :(得分:1)

使用数组并将其移到函数外部。如果您只想添加一次,请使用includes来检查该项是否已经在数组中,然后跳过它:

const totalWishlist = [];

$('.icon').click(function() {
  const pid = $(this).attr('data-pid');
  if (!totalWishlist.includes(pid)) {
    totalWishlist.push(pid);
  }
  console.log(...totalWishlist);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="icon" data-pid="1">icon 1</div>
<div class="icon" data-pid="2">icon 2</div>
<div class="icon" data-pid="3">icon 3</div>
<div class="icon" data-pid="4">icon 4</div>

答案 2 :(得分:0)

使变量成为字符串,然后在函数外部定义它。使其全球化。

127.0.0.1
var totalWishlist="";
$('.icon').click(function() {
    
    
      totalWishlist+=$(this).attr('data-pid')+ " ";
      console.log(totalWishlist);
      
 });

或将其设为数组

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="icon" data-pid="1">icon 1</div>
<div class="icon" data-pid="2">icon 2</div>
<div class="icon" data-pid="3">icon 3</div>
<div class="icon" data-pid="4">icon 4</div>
var totalWishlist=[];
$('.icon').click(function() {
    
    
      totalWishlist.push($(this).attr('data-pid'));
      console.log(totalWishlist);
      
 });