繁体   English   中英

如何在Javascript中增加对象内的唯一值

[英]How to increment unique value inside an object in Javascript

这是我关于stackoverflow的第一个问题。

$("button").click(function(){
  var text = "<ul>";
  var item = $(".inputvalue").val();
  var n = checkvalue(myArray, item);
  if (!n)
  {
    myArray.push(item);
  }
  else
  {
    counter++;
  }
  for (var i = 0; i < myArray.length; i++)
  {
    var valuetostring = "class" + i.toString();
    text += "<li class=" + valuetostring + ">" + myArray[i] + " x " + counter + "</li>";
  }
  $("#counter").text(counter);
  document.getElementById("output").innerHTML = text;
});

https://jsfiddle.net/m3Low41j/2/

我需要这种解决方案,以便在键入新值时向数组添加一个唯一值。如果键入相同的值,则该值之后的数字应加1。

像这样:

  • 沙发x 1
  • 枕头x 4
  • 椅子x 1
  • 表x 3

我该怎么做?

我很抱歉,如果我的代码有点业余,我已经为此工作了两个晚上,现在仍然无法解决。

你能帮我一下吗? 谢谢。

您可以尝试使用如下所示的对象,然后访问该对象以进行显示而不是使用数组。 请记住,这是精简版,您需要验证输入以确保其格式适合作为对象键。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Working_with_Objects

 var inputObj = {}; var entries = function(input){ if(inputObj[input]== undefined){ inputObj[input] = 1; } else{ inputObj[input] += 1; } } entries("hello"); entries("bye"); entries("hello"); //Object.keys, gives you an array of all keys in onject console.log(Object.keys(inputObj)) //Display key property pairs for entire object Object.keys(inputObj).forEach(function(key) { console.log(key, inputObj[key]); }); //Access indivdual property console.log("Hello Property = ", inputObj.hello) 

如果您使用的是jQuery,则应继续使用该api,而不要混合使用本机和jQuery,您确实应该给变量赋予有意义的名称,以使日后您以及查看代码的其他人更容易使用。

该代码的主要优点是,您可以使用对象文字{}存储添加的项目及其数量。 所有项目将都是唯一的,因为您不能有对象的重复键。

 // use an object to store your items const items = {}; const $input = $('.inputvalue') const $output = $('#output') // create a ul with your items and their counts function render(items) { const $ul = $('<ul>') $.each(items, function(key, value) { $ul.append($(`<li>${key} x ${value}</li>`)) }) return $ul } $(".run1").click(function(e) { // get the value from the input field const item = $input.val() // if there is no item in the input return and do nothing if (item === '') { // you could show an error message here return false } // if no key for your item exists create it if (!items[item]) { // initialize to 0 items[item] = 0 } // increment your count, we can be sure we have an item at this point items[item] += 1 // render your output $output.html( render(items) ) console.log('items', items) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"> <input type="text" class="inputvalue"> <button class="run1"> RUN 1 </button> <p id="output"></p> <p id="counter"></p> </div> 

经过测试,可以正常工作!

请查看代码注释,并利用reduce函数获取Array元素的总和。

 // Global variables const arr = []; $('.run1').click(function() { let val = $('.inputvalue').val(), counterEl = $('#counter'), outputEl = $('#output'), outputHtml = '', obj = {}; // Sanitize val = $.trim(val); // Do nothing when dealing with empty values if (!val) { return; } // Add the value to the main array arr.push(val); // Create an object with totals obj = arr.reduce(function(accumulated, item){ if (accumulated[item]) { accumulated[item] += 1; } else { accumulated[item] = 1; } return accumulated; }, {}); // Build the HTML $.each(obj, function(key, count) { outputHtml += '<li>' + key + ' x ' + count + '</li>'; }); // Print the HTML and update the counter outputEl.html(outputHtml); counterEl.text(arr.length); }); 
 .box { padding: 20px; border: 1px solid #ccc; display: inline-block; float: left; margin-bottom: 20px; } /* It's always a good practice to set this cursor for buttons */ .run1 { cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"> <input type="text" class="inputvalue"> <button class="run1"> RUN 1 </button> <p id="output"></p> <p id="counter"></p> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM