简体   繁体   English

在数组的开头添加一个对象

[英]Add an object at the beginning of array

I know it's easy, but I can't quite get it. 我知道这很容易,但是我做不到。

function submitNewComment() {
   var noo = 0; //array index
   var userName = document.getElementById('user-name').value; //textbox
   var commentBox = document.getElementById('main-comment').value; //textbox
   var now = new Date();
   mili = now.getTime(); //time in milisecond
   var element = [];
   element.push({
      "no": noo, //array index
      "username": userName,
      "date": mili,
      "body": commentBox,
      "likes": "0",
      "parent": null
   });
console.log(element);
noo++;
console.log(noo);
}

In short, I need to add create a variable as an array containing objects. 简而言之,我需要添加一个创建变量作为包含对象的数组。 When I run the function, it doesn't quite work as I hoped. 当我运行该函数时,它并没有按照我希望的那样工作。 I am missing something. 我想念一些东西。

The problem exists when you run the function for the second time. 当您第二次运行该函数时,存在问题。 Ideally 2nd object should be created but the first one gets updated. 理想情况下,应该创建第二个对象,但第一个对象要更新。 So, at the end of 2nd run and every other run there after, length of the array remains 1. 因此,在第二次运行结束时以及此后的其他所有运行之后,数组的长度保持为1。

You have a few issues. 你有几个问题。 One you need to have a way to get the data after the page loads. 您需要一种在页面加载后获取数据的方法。

  1. You need a button or some other method of action. 您需要一个按钮或其他某种操作方法。
  2. You confusing yourself with your object creation. 您将自己与对象创建混淆了。 If it's a factory function for creating objects then 'this.[label]' is valid, but if you are just pushing form data as an object into an array then do as I've suggested below. 如果这是用于创建对象的工厂函数,则“ this。[label]”有效,但是如果您只是将表单数据作为对象推入数组,请按照下面的建议进行操作。 Does what I did make sense? 我做的有意义吗?
  3. Also I didn't change it here, but the best way to create a date in milliseconds is Date.now(). 我也没有在这里更改它,但是创建日期(以毫秒为单位)的最佳方法是Date.now()。 Use this method going forward, it'll both shorten and simplify your code. 继续使用此方法,它将缩短和简化您的代码。
  4. Any questions? 任何问题?

 var element = []; var btn = document.getElementById('btn'); btn.addEventListener('click', submitNewComment); function submitNewComment() { var userName = document.getElementById('user-name').value var commentBox = document.getElementById('main-comment').value var now = new Date(); var milliseconds = now.getTime(); element.unshift({ no: "test", username: userName, date: milliseconds, body: commentBox, likes: 0, parent: null, }); console.log(element); } 
  <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>misterhtmlcss</title> </head> <body> <input type="text" name="user-name" id="user-name"> <input type="text" name="main-comment" id="main-comment"> <button id="btn">Submit</button> <script src="index.js"></script> </body> </html> 

Update. 更新。 I realized I left this declaration inside the function meaning it wouldn't retain continuous submissions which you may have wanted based on what you did say. 我意识到我已将此声明保留在函数中,这意味着它不会保留您根据您的要求可能想要的连续提交。

Use .unshift( object ) to prepend to an array. 使用.unshift( object )前置到数组。

 let a = [1,2,3,4]; console.log( a ); a.unshift(5); console.log( a ); 

You can use Array.prototype.unshift() to add elements to the start of an Array. 您可以使用Array.prototype.unshift()将元素添加到Array的开头。 This method returns the new length of the Array. 此方法返回数组的新长度。

 var element = []; element.push({ "no": "noo", //temp variable "username": "userName", "date": "mili", "body": "commentBox", "likes": "0", "parent": null }); element.push({"something": "else"}); var newLen = element.unshift({"object": "one"}); console.log(element); console.log("New length of Element Array: "+newLen); 

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

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