I am self learning JS and working on an exercise which takes input from the user(First Name, Middle Name, Last Name), and saves the input in a JS Object (Later I will manipulate the object itself and sort it, check duplicates, etc.)
我正在自学JS,并正在做一个练习,从用户那里获取输入(姓名、中间名、姓),并将输入保存在一个JS对象中(稍后我将对对象本身进行操作并对其进行排序,检查副本等)。
I have looked everywhere and cannot find any direction on this one. I am familiar with saving HTML input as variables (var n=document.getElementById('x').value) but I am very new to objects.
我到处找遍了,找不到方向。我熟悉将HTML输入保存为变量(var n=document.getElementById('x').value),但我对对象非常陌生。
How would I save user input in objects? And can I save multiples 'submissions' in the Object as in 'load the object up from user input', and then manipulate it on a later step?
如何在对象中保存用户输入?我可以在对象中保存多个“提交”,比如“从用户输入加载对象”,然后在后面的步骤中对其进行操作吗?
HTML:
HTML:
<body>
<label>First Name:
<input type='text' name='firstName' id='firstName' placeholder="First Name">
</label>
<br>
<br>
<label>Middle Name:
<input type='text' name='middleName' id='middleName' placeholder="Middle Name">
</label>
<br>
<br>
<label>Last Name:
<input type='text' name='lastName' id='lastName' placeholder="Last Name">
</label>
<br>
<br>
<button type="button" onclick="buildList()">Add to List</button>
</body>
What I imagine the JS Object to look like, and each time the user presses 'Add to List' the program adds another First/Middle/Last name to the list.:
我想象的JS对象是什么样子的,每次用户点击“添加到列表”,程序就会在列表中添加另一个名字。
var list = {
firstName:"John",
middleName:"Will",
lastName:"Doe"
},
{
firstName:"Ben",
middleName:"Thomas",
lastName:"Smith"
},
{
firstName:"*e",
middleName:"James",
lastName:"Kanter"
};
***Note, later on I plan to count the frequency of each First/Middle/Last Name and output it on the screen.. i.e.: 'FirstName'Jason: 2, 'FirstName'Ed:3; 'MiddleName'Marie:5; 'LastName'Smith:3'
***注意,稍后我计划数一下每个姓/名/名/名的频率,并将其输出到屏幕上。即。:“FirstName 'Jason:2”,“FirstName”:3;“MiddleName 'Marie:5;“LastName 'Smith:3”
My goal: Create a list of full names. Break them out into three lists: first, middle, and last names. Count the frequency of the names in each list. ---I figured using an object would be the best way to do this.
我的目标是:创建一个全名列表。把他们分成三个名单:第一个,中间的和最后的名字。计算每个列表中名称的频率。---我认为使用一个物体是最好的方法。
6 个解决方案
#1
3
You could use a click handler like
您可以使用类似的单击处理程序
var list = [],
$ins = $('#firstName, #middleName, #lastName'),
counter = {
firstName: {},
middleName: {},
lastName: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value.trim();
if (val) {
obj[this.id] = val;
} else {
var name = this.previousSibling.nodeValue.trim();
alert(name.substring(0, name.length - 1) + ' cannot be blank');
this.focus();
valid = false;
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
$.each(obj, function(key, value) {
var count = counter[key][value] || 0;
counter[key][value] = count + 1;
});
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
$('pre').append(document.createTextNode(JSON.stringify(counter)));
})
pre {
white-space: pre-wrap;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>First Name:
<input type='text' name='firstName' id='firstName' placeholder="First Name">
</label>
<br>
<br>
<label>Middle Name:
<input type='text' name='middleName' id='middleName' placeholder="Middle Name">
</label>
<br>
<br>
<label>Last Name:
<input type='text' name='lastName' id='lastName' placeholder="Last Name">
</label>
<br>
<br>
<button type="button" id="add">Add to List</button>
<button type="button" id="print">Print</button>
<pre></pre>
#2
1
Js objects are very easy to manipulate (which many times makes it prone to more errors). If you want to add a property just put some value on it.
Js对象非常容易操作(这使得它容易出现更多的错误)。如果你想添加一个属性,只要给它赋值。
var info = {};//create an empty object
info.firstName = document.getElementById('firstName').value;
info.lastName = document.getElementById('lastName').value;
allInfo.push(info);//you had to initialize the array before
#3
0
If your goal is to map the frequency of each name, using three hashes might be the most efficient option. As an example for just one of the inputs:
如果您的目标是映射每个名称的频率,那么使用三个散列可能是最有效的选择。作为其中一个输入的例子:
var firstNames = {};
function setFirstName(firstName){
if(firstNames[firstName] === undefined){
firstNames[firstName] = 1;
return;
}
firstNames[firstName]++;
}
function buildList(){
setFirstName(document.getElementById('firstName').value);
}
That way you'll end up with something like var firstNames = {tom: 3, dick: 10, harry: 2, ...}
. Here's a fiddle: https://jsfiddle.net/n3yhu6as/2/
这样你就会得到诸如var firstNames = {tom: 3, dick: 10, harry: 2,…}之类的东西。这是一个小提琴:https://jsfiddle.net/n3yhu6as/2/
#4
0
You could create an object from the inputs (as they look in given markup), like:
您可以从输入中创建一个对象(正如它们在给定的标记中所看到的那样),比如:
function buildList(){
var list = {};
$("body").find("input").each(function() {
var field= $(this).attr('id');
var value= $(this).val();
list[field] = value;
});
}
小提琴。
#5
0
There is a difference between [] and {}
[]和{}之间存在差异
The push() method and length property is only applicable to [] becuase it actually the JavaScript array
push()方法和length属性只适用于[],因为它实际上是JavaScript数组
Therefore in your case you should put your JSON Object inside a JSON Array
因此,在这种情况下,应该将JSON对象放在JSON数组中
var list = [{
firstName:"John",
middleName:"Will",
lastName:"Doe"
},
{
firstName:"Ben",
middleName:"Thomas",
lastName:"Smith"
},
{
firstName:"*e",
middleName:"James",
lastName:"Kanter"
}];
If you do like this then you do code in your button click event as
如果您这样做,那么您就在按钮单击事件as中执行代码
list.push({
firstName: document.getElementById("firstName").value,
middleName: document.getElementById("middleName").value,
lastName: document.getElementById("lastName").value
});
#6
0
how to search for a particular keyword from the user provided name fields.
如何从用户提供的名称字段中搜索特定的关键字。
var list = [],
$ins = $('#firstName, #middleName, #lastName'),
counter = {
firstName: {},
middleName: {},
lastName: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value.trim();
if (val) {
obj[this.id] = val;
} else {
var name = this.previousSibling.nodeValue.trim();
alert(name.substring(0, name.length - 1) + ' cannot be blank');
this.focus();
valid = false;
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
$.each(obj, function(key, value) {
var count = counter[key][value] || 0;
counter[key][value] = count + 1;
});
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
$('pre').append(document.createTextNode(JSON.stringify(counter)));
})
pre {
white-space: pre-wrap;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>First Name:
<input type='text' name='firstName' id='firstName' placeholder="First Name">
</label>
<br>
<br>
<label>Middle Name:
<input type='text' name='middleName' id='middleName' placeholder="Middle Name">
</label>
<br>
<br>
<label>Last Name:
<input type='text' name='lastName' id='lastName' placeholder="Last Name">
</label>
<br>
<br>
<button type="button" id="add">Add to List</button>
<button type="button" id="print">Print</button>
<pre></pre>
#1
3
You could use a click handler like
您可以使用类似的单击处理程序
var list = [],
$ins = $('#firstName, #middleName, #lastName'),
counter = {
firstName: {},
middleName: {},
lastName: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value.trim();
if (val) {
obj[this.id] = val;
} else {
var name = this.previousSibling.nodeValue.trim();
alert(name.substring(0, name.length - 1) + ' cannot be blank');
this.focus();
valid = false;
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
$.each(obj, function(key, value) {
var count = counter[key][value] || 0;
counter[key][value] = count + 1;
});
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
$('pre').append(document.createTextNode(JSON.stringify(counter)));
})
pre {
white-space: pre-wrap;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>First Name:
<input type='text' name='firstName' id='firstName' placeholder="First Name">
</label>
<br>
<br>
<label>Middle Name:
<input type='text' name='middleName' id='middleName' placeholder="Middle Name">
</label>
<br>
<br>
<label>Last Name:
<input type='text' name='lastName' id='lastName' placeholder="Last Name">
</label>
<br>
<br>
<button type="button" id="add">Add to List</button>
<button type="button" id="print">Print</button>
<pre></pre>
#2
1
Js objects are very easy to manipulate (which many times makes it prone to more errors). If you want to add a property just put some value on it.
Js对象非常容易操作(这使得它容易出现更多的错误)。如果你想添加一个属性,只要给它赋值。
var info = {};//create an empty object
info.firstName = document.getElementById('firstName').value;
info.lastName = document.getElementById('lastName').value;
allInfo.push(info);//you had to initialize the array before
#3
0
If your goal is to map the frequency of each name, using three hashes might be the most efficient option. As an example for just one of the inputs:
如果您的目标是映射每个名称的频率,那么使用三个散列可能是最有效的选择。作为其中一个输入的例子:
var firstNames = {};
function setFirstName(firstName){
if(firstNames[firstName] === undefined){
firstNames[firstName] = 1;
return;
}
firstNames[firstName]++;
}
function buildList(){
setFirstName(document.getElementById('firstName').value);
}
That way you'll end up with something like var firstNames = {tom: 3, dick: 10, harry: 2, ...}
. Here's a fiddle: https://jsfiddle.net/n3yhu6as/2/
这样你就会得到诸如var firstNames = {tom: 3, dick: 10, harry: 2,…}之类的东西。这是一个小提琴:https://jsfiddle.net/n3yhu6as/2/
#4
0
You could create an object from the inputs (as they look in given markup), like:
您可以从输入中创建一个对象(正如它们在给定的标记中所看到的那样),比如:
function buildList(){
var list = {};
$("body").find("input").each(function() {
var field= $(this).attr('id');
var value= $(this).val();
list[field] = value;
});
}
小提琴。
#5
0
There is a difference between [] and {}
[]和{}之间存在差异
The push() method and length property is only applicable to [] becuase it actually the JavaScript array
push()方法和length属性只适用于[],因为它实际上是JavaScript数组
Therefore in your case you should put your JSON Object inside a JSON Array
因此,在这种情况下,应该将JSON对象放在JSON数组中
var list = [{
firstName:"John",
middleName:"Will",
lastName:"Doe"
},
{
firstName:"Ben",
middleName:"Thomas",
lastName:"Smith"
},
{
firstName:"*e",
middleName:"James",
lastName:"Kanter"
}];
If you do like this then you do code in your button click event as
如果您这样做,那么您就在按钮单击事件as中执行代码
list.push({
firstName: document.getElementById("firstName").value,
middleName: document.getElementById("middleName").value,
lastName: document.getElementById("lastName").value
});
#6
0
how to search for a particular keyword from the user provided name fields.
如何从用户提供的名称字段中搜索特定的关键字。
var list = [],
$ins = $('#firstName, #middleName, #lastName'),
counter = {
firstName: {},
middleName: {},
lastName: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value.trim();
if (val) {
obj[this.id] = val;
} else {
var name = this.previousSibling.nodeValue.trim();
alert(name.substring(0, name.length - 1) + ' cannot be blank');
this.focus();
valid = false;
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
$.each(obj, function(key, value) {
var count = counter[key][value] || 0;
counter[key][value] = count + 1;
});
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
$('pre').append(document.createTextNode(JSON.stringify(counter)));
})
pre {
white-space: pre-wrap;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>First Name:
<input type='text' name='firstName' id='firstName' placeholder="First Name">
</label>
<br>
<br>
<label>Middle Name:
<input type='text' name='middleName' id='middleName' placeholder="Middle Name">
</label>
<br>
<br>
<label>Last Name:
<input type='text' name='lastName' id='lastName' placeholder="Last Name">
</label>
<br>
<br>
<button type="button" id="add">Add to List</button>
<button type="button" id="print">Print</button>
<pre></pre>