[英]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.
您需要一种在页面加载后获取数据的方法。
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.