这是我到目前为止所做的:
var onepage = [{
name: 'Custom Design',
hours: 5
},{
name: 'Premium Theme',
hours: 2
},{
name: 'SEO',
hours: 5
},{
name: 'Backlink Building',
hours: 6
},{
name: 'Article Writing',
hours: 7
},{
name: 'Copywriting',
hours: 3
},{
name: 'Development',
hours: 8
}
]
window.onkeyup = keyup;
var numberofPages;
function keyup(e) {
numberofPages = e.target.value;
newHours = [];
for (var i = 0; i < onepage.length; i++) {
var totalHours = numberofPages * onepage[i].hours;
newHours.push(totalHours);
}
console.log(newHours);
}
&#13;
<input type="text" placeholder="Number of Pages" id="pages" value="1">
&#13;
用户输入页数#并将其乘以hours
并推入数组newHours
,然后从那里我想更新原始对象数组小时。
我不确定如何update
,或者创建一个新的对象数组是否有意义?
答案 0 :(得分:2)
您可以直接更新阵列而无需创建newArray。请注意,直接更新原始数组hours
会导致意外结果。因此,添加了新属性calculatedHours
var onepage = [{name: 'Custom Design',hours: 5},{name: 'Premium Theme',hours: 2},{name: 'SEO',hours: 5},{name: 'Backlink Building',hours: 6},{name: 'Article Writing',hours: 7},{name: 'Copywriting',hours: 3},{name: 'Development',hours: 8}];
window.onkeyup = keyup;
var numberofPages;
function keyup(e) {
numberofPages = e.target.value;
newHours = [];
for (var i = 0; i < onepage.length; i++) {
onepage[i].calculatedHours = numberofPages * onepage[i].hours;
}
console.log(onepage);
}
&#13;
<input type="text" placeholder="Number of Pages" id="pages" value="1">
&#13;
答案 1 :(得分:0)
只需执行一个简单的forEach循环,如下所示。我已创建它,以便在用户按下输入内的回车键(13)后更新。我建议将监听器放在输入上,而不是在实际代码中的窗口上。
document.getElementById('foo').addEventListener('keyup', e => {
if (e.keyCode !== 13) return;
onepage.forEach(el => el.computed = el.hours * e.target.value);
console.log(onepage);
})
<input id="foo">
<script>
var onepage = [
{
name: 'Custom Design',
hours: 5
},
{
name: 'Premium Theme',
hours: 2
},
{
name: 'SEO',
hours: 5
},
{
name: 'Backlink Building',
hours: 6
},
{
name: 'Article Writing',
hours: 7
},
{
name: 'Copywriting',
hours: 3
},
{
name: 'Development',
hours: 8
}
]
</script>